i18n.ts 43.0 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';

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

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

20
const NUMBER_OF_CONCURRENT_DOWNLOADS = 4;
21

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
}

D
Dirk Baeumer 已提交
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
export interface Language {
	id: string; // laguage id, e.g. zh-tw, de
	transifexId?: string; // language id used in transifex, e.g zh-hant, de (optional, if not set, the id is used)
	folderName?: string; // language specific folder name, e.g. cht, deu  (optional, if not set, the id is used)
}

export interface InnoSetup {
	codePage: string; //code page for encoding (http://www.jrsoftware.org/ishelp/index.php?topic=langoptionssection)
	defaultInfo?: {
		name: string; // inno setup language name
		id: string; // locale identifier (https://msdn.microsoft.com/en-us/library/dd318693.aspx)
	};
}

export const defaultLanguages: Language[] = [
	{ id: 'zh-tw', folderName: 'cht', transifexId: 'zh-hant' },
	{ id: 'zh-cn', folderName: 'chs', transifexId: 'zh-hans' },
	{ id: 'ja', folderName: 'jpn' },
	{ id: 'ko', folderName: 'kor' },
	{ id: 'de', folderName: 'deu' },
	{ id: 'fr', folderName: 'fra' },
	{ id: 'es', folderName: 'esn' },
	{ id: 'ru', folderName: 'rus' },
	{ id: 'it', folderName: 'ita' }
];

// languages requested by the community to non-stable builds
export const extraLanguages: Language[] = [
	{ id: 'pt-br', folderName: 'ptb' },
	{ id: 'hu', folderName: 'hun' },
	{ id: 'tr', folderName: 'trk' }
];

59
// non built-in extensions also that are transifex and need to be part of the language packs
60 61 62 63 64 65
const externalExtensionsWithTranslations = {
	'vscode-chrome-debug': 'msjsdiag.debugger-for-chrome',
	'vscode-node-debug': 'ms-vscode.node-debug',
	'vscode-node-debug2': 'ms-vscode.node-debug2'
};

66

D
Dirk Baeumer 已提交
67 68 69 70
interface Map<V> {
	[key: string]: V;
}

71 72 73
interface Item {
	id: string;
	message: string;
74
	comment?: string;
75 76
}

77
export interface Resource {
78 79 80 81
	name: string;
	project: string;
}

82 83 84 85 86 87
interface ParsedXLF {
	messages: Map<string>;
	originalFilePath: string;
	language: string;
}

D
Dirk Baeumer 已提交
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
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);
	}
}

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 145 146 147 148 149 150 151 152 153
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));
	}
}

D
Dirk Baeumer 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 167
interface BundledExtensionHeaderFormat {
	id: string;
	type: string;
	hash: string;
	outDir: string;
}

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

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
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 已提交
200
	private buffer: string[];
201
	private files: Map<Item[]>;
202
	public numberOfMessages: number;
203

J
Joao Moreno 已提交
204 205
	constructor(public project: string) {
		this.buffer = [];
206
		this.files = Object.create(null);
207
		this.numberOfMessages = 0;
208 209
	}

J
Joao Moreno 已提交
210 211
	public toString(): string {
		this.appendHeader();
212 213 214 215 216 217

		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 已提交
218
			this.appendNewLine('</body></file>', 2);
219 220 221 222 223 224
		}

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

D
Dirk Baeumer 已提交
225
	public addFile(original: string, keys: (string | LocalizeInfo)[], messages: string[]) {
226 227 228 229
		if (keys.length === 0) {
			console.log('No keys in ' + original);
			return;
		}
D
Dirk Baeumer 已提交
230 231 232
		if (keys.length !== messages.length) {
			throw new Error(`Unmatching keys(${keys.length}) and messages(${messages.length}).`);
		}
233
		this.numberOfMessages += keys.length;
234
		this.files[original] = [];
D
Dirk Baeumer 已提交
235 236 237
		let existingKeys = new Set<string>();
		for (let i = 0; i < keys.length; i++) {
			let key = keys[i];
238 239
			let realKey: string | undefined;
			let comment: string | undefined;
240
			if (Is.string(key)) {
D
Dirk Baeumer 已提交
241 242 243 244 245 246
				realKey = key;
				comment = undefined;
			} else if (LocalizeInfo.is(key)) {
				realKey = key.key;
				if (key.comment && key.comment.length > 0) {
					comment = key.comment.map(comment => encodeEntities(comment)).join('\r\n');
247 248
				}
			}
D
Dirk Baeumer 已提交
249 250 251 252 253 254
			if (!realKey || existingKeys.has(realKey)) {
				continue;
			}
			existingKeys.add(realKey);
			let message: string = encodeEntities(messages[i]);
			this.files[original].push({ id: realKey, message: message, comment: comment });
255 256 257
		}
	}

J
Joao Moreno 已提交
258 259
	private addStringItem(item: Item): void {
		if (!item.id || !item.message) {
D
Dirk Baeumer 已提交
260
			throw new Error(`No item ID or value specified: ${JSON.stringify(item)}`);
J
Joao Moreno 已提交
261
		}
262

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

J
Joao Moreno 已提交
266 267 268
		if (item.comment) {
			this.appendNewLine(`<note>${item.comment}</note>`, 6);
		}
269

J
Joao Moreno 已提交
270
		this.appendNewLine('</trans-unit>', 4);
271 272
	}

J
Joao Moreno 已提交
273 274 275
	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);
276 277
	}

J
Joao Moreno 已提交
278 279 280
	private appendFooter(): void {
		this.appendNewLine('</xliff>', 0);
	}
281

J
Joao Moreno 已提交
282 283 284 285 286
	private appendNewLine(content: string, indent?: number): void {
		let line = new Line(indent);
		line.append(content);
		this.buffer.push(line.toString());
	}
287

288 289 290 291
	static parsePseudo = function (xlfString: string): Promise<ParsedXLF[]> {
		return new Promise((resolve, reject) => {
			let parser = new xml2js.Parser();
			let files: { messages: Map<string>, originalFilePath: string, language: string }[] = [];
M
Matt Bierner 已提交
292
			parser.parseString(xlfString, function (err: any, result: any) {
293
				const fileNodes: any[] = result['xliff']['file'];
294
				fileNodes.forEach(file => {
295
					const originalFilePath = file.$.original;
296
					const messages: Map<string> = {};
297
					const transUnits = file.body[0]['trans-unit'];
298
					if (transUnits) {
M
Matt Bierner 已提交
299
						transUnits.forEach((unit: any) => {
300 301 302 303 304 305 306 307
							const key = unit.$.id;
							const val = pseudify(unit.source[0]['_'].toString());
							if (key && val) {
								messages[key] = decodeEntities(val);
							}
						});
						files.push({ messages: messages, originalFilePath: originalFilePath, language: 'ps' });
					}
308
				});
309
				resolve(files);
310 311 312 313
			});
		});
	};

J
Joao Moreno 已提交
314
	static parse = function (xlfString: string): Promise<ParsedXLF[]> {
315 316 317 318 319
		return new Promise((resolve, reject) => {
			let parser = new xml2js.Parser();

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

M
Matt Bierner 已提交
320
			parser.parseString(xlfString, function (err: any, result: any) {
321
				if (err) {
D
Dirk Baeumer 已提交
322
					reject(new Error(`XLF parsing error: Failed to parse XLIFF string. ${err}`));
323 324 325 326
				}

				const fileNodes: any[] = result['xliff']['file'];
				if (!fileNodes) {
D
Dirk Baeumer 已提交
327
					reject(new Error(`XLF parsing error: XLIFF file does not contain "xliff" or "file" node(s) required for parsing.`));
328 329 330 331 332
				}

				fileNodes.forEach((file) => {
					const originalFilePath = file.$.original;
					if (!originalFilePath) {
D
Dirk Baeumer 已提交
333
						reject(new Error(`XLF parsing error: XLIFF file node does not contain original attribute to determine the original location of the resource file.`));
334
					}
335
					let language = file.$['target-language'];
336
					if (!language) {
D
Dirk Baeumer 已提交
337
						reject(new Error(`XLF parsing error: XLIFF file node does not contain target-language attribute to determine translated language.`));
338
					}
339
					const messages: Map<string> = {};
340 341

					const transUnits = file.body[0]['trans-unit'];
342
					if (transUnits) {
M
Matt Bierner 已提交
343
						transUnits.forEach((unit: any) => {
344 345 346 347 348 349 350 351 352 353 354 355 356 357
							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(new Error(`XLF parsing error: 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.toLowerCase() });
					}
358 359 360 361 362 363 364 365
				});

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

366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
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) => {
D
Dirk Baeumer 已提交
387
			this.outstandingPromises.push({ factory, c, e });
388 389 390 391 392 393
			this.consume();
		});
	}

	private consume(): void {
		while (this.outstandingPromises.length && this.runningPromises < this.maxDegreeOfParalellism) {
394
			const iLimitedTask = this.outstandingPromises.shift()!;
395 396 397 398 399 400 401 402 403 404 405 406 407 408
			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 已提交
409 410 411
function sortLanguages(languages: Language[]): Language[] {
	return languages.sort((a: Language, b: Language): number => {
		return a.id < b.id ? -1 : (a.id > b.id ? 1 : 0);
D
Dirk Baeumer 已提交
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
	});
}

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 已提交
432
				return m4[length - 2] === '\r' ? '\r\n' : '\n';
D
Dirk Baeumer 已提交
433 434 435 436 437 438 439 440 441
			} else {
				return '';
			}
		} else {
			// We match a string
			return match;
		}
	});
	return result;
442
}
D
Dirk Baeumer 已提交
443

J
Joao Moreno 已提交
444 445
function escapeCharacters(value: string): string {
	var result: string[] = [];
D
Dirk Baeumer 已提交
446 447
	for (var i = 0; i < value.length; i++) {
		var ch = value.charAt(i);
J
Joao Moreno 已提交
448
		switch (ch) {
D
Dirk Baeumer 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
			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('');
}

D
Dirk Baeumer 已提交
480
function processCoreBundleFormat(fileHeader: string, languages: Language[], json: BundledFormat, emitter: ThroughStream) {
D
Dirk Baeumer 已提交
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
	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++;
D
Dirk Baeumer 已提交
501
			if (typeof key === 'string') {
D
Dirk Baeumer 已提交
502 503 504 505 506 507 508 509
				messageMap[key] = messages[i];
			} else {
				messageMap[key.key] = messages[i];
			}
		});
	});

	let languageDirectory = path.join(__dirname, '..', '..', 'i18n');
D
Dirk Baeumer 已提交
510 511
	let sortedLanguages = sortLanguages(languages);
	sortedLanguages.forEach((language) => {
J
Joao Moreno 已提交
512
		if (process.env['VSCODE_BUILD_VERBOSE']) {
D
Dirk Baeumer 已提交
513
			log(`Generating nls bundles for: ${language.id}`);
J
Joao Moreno 已提交
514 515
		}

D
Dirk Baeumer 已提交
516
		statistics[language.id] = 0;
D
Dirk Baeumer 已提交
517
		let localizedModules: Map<string[]> = Object.create(null);
D
Dirk Baeumer 已提交
518 519
		let languageFolderName = language.folderName || language.id;
		let cwd = path.join(languageDirectory, languageFolderName, 'src');
D
Dirk Baeumer 已提交
520 521 522
		modules.forEach((module) => {
			let order = keysSection[module];
			let i18nFile = path.join(cwd, module) + '.i18n.json';
523
			let messages: Map<string> | null = null;
D
Dirk Baeumer 已提交
524 525 526 527
			if (fs.existsSync(i18nFile)) {
				let content = stripComments(fs.readFileSync(i18nFile, 'utf8'));
				messages = JSON.parse(content);
			} else {
J
Joao Moreno 已提交
528 529 530
				if (process.env['VSCODE_BUILD_VERBOSE']) {
					log(`No localized messages found for module ${module}. Using default messages.`);
				}
D
Dirk Baeumer 已提交
531
				messages = defaultMessages[module];
D
Dirk Baeumer 已提交
532
				statistics[language.id] = statistics[language.id] + Object.keys(messages).length;
D
Dirk Baeumer 已提交
533 534 535
			}
			let localizedMessages: string[] = [];
			order.forEach((keyInfo) => {
536
				let key: string | null = null;
D
Dirk Baeumer 已提交
537
				if (typeof keyInfo === 'string') {
D
Dirk Baeumer 已提交
538 539 540 541
					key = keyInfo;
				} else {
					key = keyInfo.key;
				}
542
				let message: string = messages![key];
D
Dirk Baeumer 已提交
543
				if (!message) {
J
Joao Moreno 已提交
544 545 546
					if (process.env['VSCODE_BUILD_VERBOSE']) {
						log(`No localized message found for key ${key} in module ${module}. Using default message.`);
					}
D
Dirk Baeumer 已提交
547
					message = defaultMessages[module][key];
D
Dirk Baeumer 已提交
548
					statistics[language.id] = statistics[language.id] + 1;
D
Dirk Baeumer 已提交
549 550 551 552 553 554 555 556
				}
				localizedMessages.push(message);
			});
			localizedModules[module] = localizedMessages;
		});
		Object.keys(bundleSection).forEach((bundle) => {
			let modules = bundleSection[bundle];
			let contents: string[] = [
A
Alex Dima 已提交
557
				fileHeader,
D
Dirk Baeumer 已提交
558
				`define("${bundle}.nls.${language.id}", {`
D
Dirk Baeumer 已提交
559 560 561 562 563 564 565 566 567
			];
			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 已提交
568
					contents.push(`\t\t"${escapeCharacters(message)}${index < messages.length ? '",' : '"'}`);
D
Dirk Baeumer 已提交
569 570 571 572
				});
				contents.push(index < modules.length - 1 ? '\t],' : '\t]');
			});
			contents.push('});');
573
			emitter.queue(new File({ path: bundle + '.nls.' + language.id + '.js', contents: Buffer.from(contents.join('\n'), 'utf-8') }));
D
Dirk Baeumer 已提交
574 575 576 577
		});
	});
	Object.keys(statistics).forEach(key => {
		let value = statistics[key];
J
Joao Moreno 已提交
578
		log(`${key} has ${value} untranslated strings.`);
D
Dirk Baeumer 已提交
579
	});
D
Dirk Baeumer 已提交
580 581 582 583
	sortedLanguages.forEach(language => {
		let stats = statistics[language.id];
		if (Is.undef(stats)) {
			log(`\tNo translations found for language ${language.id}. Using default language instead.`);
D
Dirk Baeumer 已提交
584 585 586 587
		}
	});
}

D
Dirk Baeumer 已提交
588 589
export function processNlsFiles(opts: { fileHeader: string; languages: Language[] }): ThroughStream {
	return through(function (this: ThroughStream, file: File) {
D
Dirk Baeumer 已提交
590 591 592 593
		let fileName = path.basename(file.path);
		if (fileName === 'nls.metadata.json') {
			let json = null;
			if (file.isBuffer()) {
594
				json = JSON.parse((<Buffer>file.contents).toString('utf8'));
D
Dirk Baeumer 已提交
595
			} else {
J
Joao Moreno 已提交
596
				this.emit('error', `Failed to read component file: ${file.relative}`);
D
Dirk Baeumer 已提交
597
				return;
D
Dirk Baeumer 已提交
598 599
			}
			if (BundledFormat.is(json)) {
600
				processCoreBundleFormat(opts.fileHeader, opts.languages, json, this);
D
Dirk Baeumer 已提交
601 602
			}
		}
D
Dirk Baeumer 已提交
603
		this.queue(file);
D
Dirk Baeumer 已提交
604
	});
605 606
}

607
const editorProject: string = 'vscode-editor',
608
	workbenchProject: string = 'vscode-workbench',
609
	extensionsProject: string = 'vscode-extensions',
610
	setupProject: string = 'vscode-setup';
611

612
export function getResource(sourceFile: string): Resource {
613 614
	let resource: string;

J
Joao Moreno 已提交
615
	if (/^vs\/platform/.test(sourceFile)) {
616
		return { name: 'vs/platform', project: editorProject };
J
Joao Moreno 已提交
617
	} else if (/^vs\/editor\/contrib/.test(sourceFile)) {
618
		return { name: 'vs/editor/contrib', project: editorProject };
J
Joao Moreno 已提交
619
	} else if (/^vs\/editor/.test(sourceFile)) {
620
		return { name: 'vs/editor', project: editorProject };
J
Joao Moreno 已提交
621
	} else if (/^vs\/base/.test(sourceFile)) {
622
		return { name: 'vs/base', project: editorProject };
J
Joao Moreno 已提交
623
	} else if (/^vs\/code/.test(sourceFile)) {
624
		return { name: 'vs/code', project: workbenchProject };
J
Joao Moreno 已提交
625
	} else if (/^vs\/workbench\/parts/.test(sourceFile)) {
626 627
		resource = sourceFile.split('/', 4).join('/');
		return { name: resource, project: workbenchProject };
J
Joao Moreno 已提交
628
	} else if (/^vs\/workbench\/services/.test(sourceFile)) {
629 630
		resource = sourceFile.split('/', 4).join('/');
		return { name: resource, project: workbenchProject };
J
Joao Moreno 已提交
631
	} else if (/^vs\/workbench/.test(sourceFile)) {
632 633 634
		return { name: 'vs/workbench', project: workbenchProject };
	}

J
Joao Moreno 已提交
635
	throw new Error(`Could not identify the XLF bundle for ${sourceFile}`);
636 637 638
}


D
Dirk Baeumer 已提交
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
export function createXlfFilesForCoreBundle(): ThroughStream {
	return through(function (this: ThroughStream, file: File) {
		const basename = path.basename(file.path);
		if (basename === 'nls.metadata.json') {
			if (file.isBuffer()) {
				const xlfs: Map<XLF> = Object.create(null);
				const json: BundledFormat = JSON.parse((file.contents as Buffer).toString('utf8'));
				for (let coreModule in json.keys) {
					const projectResource = getResource(coreModule);
					const resource = projectResource.name;
					const project = projectResource.project;

					const keys = json.keys[coreModule];
					const messages = json.messages[coreModule];
					if (keys.length !== messages.length) {
						this.emit('error', `There is a mismatch between keys and messages in ${file.relative} for module ${coreModule}`);
						return;
					} else {
						let xlf = xlfs[resource];
						if (!xlf) {
							xlf = new XLF(project);
							xlfs[resource] = xlf;
						}
						xlf.addFile(`src/${coreModule}`, keys, messages);
					}
				}
				for (let resource in xlfs) {
					const xlf = xlfs[resource];
					const filePath = `${xlf.project}/${resource.replace(/\//g, '_')}.xlf`;
					const xlfFile = new File({
						path: filePath,
670
						contents: Buffer.from(xlf.toString(), 'utf8')
D
Dirk Baeumer 已提交
671 672 673 674 675 676 677 678 679 680
					});
					this.queue(xlfFile);
				}
			} else {
				this.emit('error', new Error(`File ${file.relative} is not using a buffer content`));
				return;
			}
		} else {
			this.emit('error', new Error(`File ${file.relative} is not a core meta data file.`));
			return;
681
		}
D
Dirk Baeumer 已提交
682
	});
683 684
}

D
Dirk Baeumer 已提交
685 686 687 688 689 690 691 692
export function createXlfFilesForExtensions(): ThroughStream {
	let counter: number = 0;
	let folderStreamEnded: boolean = false;
	let folderStreamEndEmitted: boolean = false;
	return through(function (this: ThroughStream, extensionFolder: File) {
		const folderStream = this;
		const stat = fs.statSync(extensionFolder.path);
		if (!stat.isDirectory()) {
693 694
			return;
		}
D
Dirk Baeumer 已提交
695 696
		let extensionName = path.basename(extensionFolder.path);
		if (extensionName === 'node_modules') {
697 698
			return;
		}
D
Dirk Baeumer 已提交
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
		counter++;
		let _xlf: XLF;
		function getXlf() {
			if (!_xlf) {
				_xlf = new XLF(extensionsProject);
			}
			return _xlf;
		}
		gulp.src([`./extensions/${extensionName}/package.nls.json`, `./extensions/${extensionName}/**/nls.metadata.json`]).pipe(through(function (file: File) {
			if (file.isBuffer()) {
				const buffer: Buffer = file.contents as Buffer;
				const basename = path.basename(file.path);
				if (basename === 'package.nls.json') {
					const json: PackageJsonFormat = JSON.parse(buffer.toString('utf8'));
					const keys = Object.keys(json);
					const messages = keys.map((key) => {
						const value = json[key];
						if (Is.string(value)) {
							return value;
						} else if (value) {
							return value.message;
						} else {
							return `Unknown message for key: ${key}`;
						}
					});
					getXlf().addFile(`extensions/${extensionName}/package`, keys, messages);
				} else if (basename === 'nls.metadata.json') {
					const json: BundledExtensionFormat = JSON.parse(buffer.toString('utf8'));
					const relPath = path.relative(`./extensions/${extensionName}`, path.dirname(file.path));
					for (let file in json) {
						const fileContent = json[file];
						getXlf().addFile(`extensions/${extensionName}/${relPath}/${file}`, fileContent.keys, fileContent.messages);
					}
				} else {
					this.emit('error', new Error(`${file.path} is not a valid extension nls file`));
					return;
				}
			}
		}, function () {
			if (_xlf) {
				let xlfFile = new File({
					path: path.join(extensionsProject, extensionName + '.xlf'),
741
					contents: Buffer.from(_xlf.toString(), 'utf8')
D
Dirk Baeumer 已提交
742 743 744 745 746 747 748 749
				});
				folderStream.queue(xlfFile);
			}
			this.queue(null);
			counter--;
			if (counter === 0 && folderStreamEnded && !folderStreamEndEmitted) {
				folderStreamEndEmitted = true;
				folderStream.queue(null);
750
			}
D
Dirk Baeumer 已提交
751 752 753 754 755 756
		}));
	}, function () {
		folderStreamEnded = true;
		if (counter === 0) {
			folderStreamEndEmitted = true;
			this.queue(null);
757 758
		}
	});
D
Dirk Baeumer 已提交
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
}

export function createXlfFilesForIsl(): ThroughStream {
	return through(function (this: ThroughStream, file: File) {
		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';
		}

		let xlf = new XLF(projectName),
			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) {
				throw new Error(`Badly formatted message found: ${line}`);
			} else {
				let key = sections[0];
				let value = sections[1];
				if (key.length > 0 && value.length > 0) {
					keys.push(key);
					messages.push(value);
				}
			}
		});
807

D
Dirk Baeumer 已提交
808 809
		const originalPath = file.path.substring(file.cwd.length + 1, file.path.split('.')[0].length).replace(/\\/g, '/');
		xlf.addFile(originalPath, keys, messages);
810

D
Dirk Baeumer 已提交
811 812
		// Emit only upon all ISL files combined into single XLF instance
		const newFilePath = path.join(projectName, resourceFile);
813
		const xlfFile = new File({ path: newFilePath, contents: Buffer.from(xlf.toString(), 'utf-8') });
D
Dirk Baeumer 已提交
814 815
		this.queue(xlfFile);
	});
816 817
}

818
export function pushXlfFiles(apiHostname: string, username: string, password: string): ThroughStream {
819 820
	let tryGetPromises: Array<Promise<boolean>> = [];
	let updateCreatePromises: Array<Promise<boolean>> = [];
821

D
Dirk Baeumer 已提交
822
	return through(function (this: ThroughStream, file: File) {
823 824 825
		const project = path.dirname(file.relative);
		const fileName = path.basename(file.path);
		const slug = fileName.substr(0, fileName.length - '.xlf'.length);
826
		const credentials = `${username}:${password}`;
827 828

		// Check if resource already exists, if not, then create it.
829
		let promise = tryGetResource(project, slug, apiHostname, credentials);
830 831
		tryGetPromises.push(promise);
		promise.then(exists => {
832
			if (exists) {
833
				promise = updateResource(project, slug, file, apiHostname, credentials);
834
			} else {
835
				promise = createResource(project, slug, file, apiHostname, credentials);
836
			}
837 838 839
			updateCreatePromises.push(promise);
		});

J
Joao Moreno 已提交
840
	}, function () {
841 842 843
		// End the pipe only after all the communication with Transifex API happened
		Promise.all(tryGetPromises).then(() => {
			Promise.all(updateCreatePromises).then(() => {
D
Dirk Baeumer 已提交
844
				this.queue(null);
845 846
			}).catch((reason) => { throw new Error(reason); });
		}).catch((reason) => { throw new Error(reason); });
847 848 849
	});
}

850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
function getAllResources(project: string, apiHostname: string, username: string, password: string): Promise<string[]> {
	return new Promise((resolve, reject) => {
		const credentials = `${username}:${password}`;
		const options = {
			hostname: apiHostname,
			path: `/api/2/project/${project}/resources`,
			auth: credentials,
			method: 'GET'
		};

		const request = https.request(options, (res) => {
			let buffer: Buffer[] = [];
			res.on('data', (chunk: Buffer) => buffer.push(chunk));
			res.on('end', () => {
				if (res.statusCode === 200) {
					let json = JSON.parse(Buffer.concat(buffer).toString());
					if (Array.isArray(json)) {
						resolve(json.map(o => o.slug));
						return;
					}
					reject(`Unexpected data format. Response code: ${res.statusCode}.`);
				} else {
					reject(`No resources in ${project} returned no data. Response code: ${res.statusCode}.`);
				}
			});
		});
		request.on('error', (err) => {
			reject(`Failed to query resources in ${project} with the following error: ${err}. ${options.path}`);
		});
		request.end();
	});
}

export function findObsoleteResources(apiHostname: string, username: string, password: string): ThroughStream {
	let resourcesByProject: Map<string[]> = Object.create(null);
885
	resourcesByProject[extensionsProject] = ([] as any[]).concat(externalExtensionsWithTranslations); // clone
886 887 888 889 890 891 892 893 894 895 896 897 898

	return through(function (this: ThroughStream, file: File) {
		const project = path.dirname(file.relative);
		const fileName = path.basename(file.path);
		const slug = fileName.substr(0, fileName.length - '.xlf'.length);

		let slugs = resourcesByProject[project];
		if (!slugs) {
			resourcesByProject[project] = slugs = [];
		}
		slugs.push(slug);
		this.push(file);
	}, function () {
899 900 901

		const json = JSON.parse(fs.readFileSync('./build/lib/i18n.resources.json', 'utf8'));
		let i18Resources = [...json.editor, ...json.workbench].map((r: Resource) => r.project + '/' + r.name.replace(/\//g, '_'));
902
		let extractedResources: string[] = [];
903 904 905 906 907 908 909 910 911 912 913 914
		for (let project of [workbenchProject, editorProject]) {
			for (let resource of resourcesByProject[project]) {
				if (resource !== 'setup_messages') {
					extractedResources.push(project + '/' + resource);
				}
			}
		}
		if (i18Resources.length !== extractedResources.length) {
			console.log(`[i18n] Obsolete resources in file 'build/lib/i18n.resources.json': JSON.stringify(${i18Resources.filter(p => extractedResources.indexOf(p) === -1)})`);
			console.log(`[i18n] Missing resources in file 'build/lib/i18n.resources.json': JSON.stringify(${extractedResources.filter(p => i18Resources.indexOf(p) === -1)})`);
		}

915
		let promises: Array<Promise<void>> = [];
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
		for (let project in resourcesByProject) {
			promises.push(
				getAllResources(project, apiHostname, username, password).then(resources => {
					let expectedResources = resourcesByProject[project];
					let unusedResources = resources.filter(resource => resource && expectedResources.indexOf(resource) === -1);
					if (unusedResources.length) {
						console.log(`[transifex] Obsolete resources in project '${project}': ${unusedResources.join(', ')}`);
					}
				})
			);
		}
		return Promise.all(promises).then(_ => {
			this.push(null);
		}).catch((reason) => { throw new Error(reason); });
	});
}

933
function tryGetResource(project: string, slug: string, apiHostname: string, credentials: string): Promise<boolean> {
934
	return new Promise((resolve, reject) => {
935 936 937 938 939 940 941
		const options = {
			hostname: apiHostname,
			path: `/api/2/project/${project}/resource/${slug}/?details`,
			auth: credentials,
			method: 'GET'
		};

942
		const request = https.request(options, (response) => {
943 944 945 946 947
			if (response.statusCode === 404) {
				resolve(false);
			} else if (response.statusCode === 200) {
				resolve(true);
			} else {
948
				reject(`Failed to query resource ${project}/${slug}. Response: ${response.statusCode} ${response.statusMessage}`);
949
			}
950 951
		});
		request.on('error', (err) => {
952
			reject(`Failed to get ${project}/${slug} on Transifex: ${err}`);
953
		});
954 955

		request.end();
956 957 958
	});
}

959 960 961 962 963 964 965 966
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'
		});
967
		const options = {
968 969 970 971 972
			hostname: apiHostname,
			path: `/api/2/project/${project}/resources`,
			headers: {
				'Content-Type': 'application/json',
				'Content-Length': Buffer.byteLength(data)
973
			},
974 975
			auth: credentials,
			method: 'POST'
976
		};
977

978
		let request = https.request(options, (res) => {
979 980 981
			if (res.statusCode === 201) {
				log(`Resource ${project}/${slug} successfully created on Transifex.`);
			} else {
982
				reject(`Something went wrong in the request creating ${slug} in ${project}. ${res.statusCode}`);
983
			}
984 985
		});
		request.on('error', (err) => {
986
			reject(`Failed to create ${project}/${slug} on Transifex: ${err}`);
987
		});
988 989 990

		request.write(data);
		request.end();
991 992 993 994 995 996 997
	});
}

/**
 * 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 已提交
998
function updateResource(project: string, slug: string, xlfFile: File, apiHostname: string, credentials: string): Promise<any> {
999 1000
	return new Promise((resolve, reject) => {
		const data = JSON.stringify({ content: xlfFile.contents.toString() });
1001
		const options = {
1002 1003 1004 1005 1006 1007 1008 1009
			hostname: apiHostname,
			path: `/api/2/project/${project}/resource/${slug}/content`,
			headers: {
				'Content-Type': 'application/json',
				'Content-Length': Buffer.byteLength(data)
			},
			auth: credentials,
			method: 'PUT'
1010
		};
1011

1012
		let request = https.request(options, (res) => {
1013
			if (res.statusCode === 200) {
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
				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();
				});
1025
			} else {
1026
				reject(`Something went wrong in the request updating ${slug} in ${project}. ${res.statusCode}`);
1027
			}
1028 1029
		});
		request.on('error', (err) => {
1030
			reject(`Failed to update ${project}/${slug} on Transifex: ${err}`);
1031
		});
1032 1033 1034

		request.write(data);
		request.end();
1035 1036 1037
	});
}

D
Dirk Baeumer 已提交
1038
// cache resources
1039
let _coreAndExtensionResources: Resource[];
D
Dirk Baeumer 已提交
1040

1041
export function pullCoreAndExtensionsXlfFiles(apiHostname: string, username: string, password: string, language: Language, externalExtensions?: Map<string>): NodeJS.ReadableStream {
1042 1043
	if (!_coreAndExtensionResources) {
		_coreAndExtensionResources = [];
D
Dirk Baeumer 已提交
1044 1045
		// editor and workbench
		const json = JSON.parse(fs.readFileSync('./build/lib/i18n.resources.json', 'utf8'));
1046 1047
		_coreAndExtensionResources.push(...json.editor);
		_coreAndExtensionResources.push(...json.workbench);
D
Dirk Baeumer 已提交
1048 1049 1050

		// extensions
		let extensionsToLocalize = Object.create(null);
1051 1052
		glob.sync('./extensions/**/*.nls.json').forEach(extension => extensionsToLocalize[extension.split('/')[2]] = true);
		glob.sync('./extensions/*/node_modules/vscode-nls').forEach(extension => extensionsToLocalize[extension.split('/')[2]] = true);
D
Dirk Baeumer 已提交
1053 1054

		Object.keys(extensionsToLocalize).forEach(extension => {
1055
			_coreAndExtensionResources.push({ name: extension, project: extensionsProject });
1056
		});
1057 1058 1059 1060 1061 1062

		if (externalExtensions) {
			for (let resourceName in externalExtensions) {
				_coreAndExtensionResources.push({ name: resourceName, project: extensionsProject });
			}
		}
1063
	}
1064
	return pullXlfFiles(apiHostname, username, password, language, _coreAndExtensionResources);
1065 1066
}

D
Dirk Baeumer 已提交
1067
export function pullSetupXlfFiles(apiHostname: string, username: string, password: string, language: Language, includeDefault: boolean): NodeJS.ReadableStream {
1068
	let setupResources = [{ name: 'setup_messages', project: workbenchProject }];
D
Dirk Baeumer 已提交
1069
	if (includeDefault) {
1070
		setupResources.push({ name: 'setup_default', project: setupProject });
1071
	}
D
Dirk Baeumer 已提交
1072 1073
	return pullXlfFiles(apiHostname, username, password, language, setupResources);
}
1074

D
Dirk Baeumer 已提交
1075
function pullXlfFiles(apiHostname: string, username: string, password: string, language: Language, resources: Resource[]): NodeJS.ReadableStream {
1076
	const credentials = `${username}:${password}`;
D
Dirk Baeumer 已提交
1077
	let expectedTranslationsCount = resources.length;
1078 1079
	let translationsRetrieved = 0, called = false;

M
Matt Bierner 已提交
1080
	return readable(function (_count: any, callback: any) {
1081 1082 1083 1084 1085 1086 1087 1088
		// Mark end of stream when all resources were retrieved
		if (translationsRetrieved === expectedTranslationsCount) {
			return this.emit('end');
		}

		if (!called) {
			called = true;
			const stream = this;
D
Dirk Baeumer 已提交
1089 1090 1091
			resources.map(function (resource) {
				retrieveResource(language, resource, apiHostname, credentials).then((file: File) => {
					if (file) {
1092
						stream.emit('data', file);
D
Dirk Baeumer 已提交
1093 1094 1095
					}
					translationsRetrieved++;
				}).catch(error => { throw new Error(error); });
1096 1097 1098 1099 1100 1101
			});
		}

		callback();
	});
}
1102
const limiter = new Limiter<File | null>(NUMBER_OF_CONCURRENT_DOWNLOADS);
1103

M
Matt Bierner 已提交
1104
function retrieveResource(language: Language, resource: Resource, apiHostname: string, credentials: string): Promise<File | null> {
1105
	return limiter.queue(() => new Promise<File | null>((resolve, reject) => {
1106 1107
		const slug = resource.name.replace(/\//g, '_');
		const project = resource.project;
1108
		let transifexLanguageId = language.id === 'ps' ? 'en' : language.transifexId || language.id;
1109 1110
		const options = {
			hostname: apiHostname,
D
Dirk Baeumer 已提交
1111
			path: `/api/2/project/${project}/resource/${slug}/translation/${transifexLanguageId}?file&mode=onlyreviewed`,
1112
			auth: credentials,
1113
			port: 443,
1114 1115
			method: 'GET'
		};
1116
		console.log('[transifex] Fetching ' + options.path);
1117

1118
		let request = https.request(options, (res) => {
J
Joao Moreno 已提交
1119 1120 1121 1122
			let xlfBuffer: Buffer[] = [];
			res.on('data', (chunk: Buffer) => xlfBuffer.push(chunk));
			res.on('end', () => {
				if (res.statusCode === 200) {
D
Dirk Baeumer 已提交
1123 1124
					resolve(new File({ contents: Buffer.concat(xlfBuffer), path: `${project}/${slug}.xlf` }));
				} else if (res.statusCode === 404) {
1125
					console.log(`[transifex] ${slug} in ${project} returned no data.`);
D
Dirk Baeumer 已提交
1126 1127 1128
					resolve(null);
				} else {
					reject(`${slug} in ${project} returned no data. Response code: ${res.statusCode}.`);
J
Joao Moreno 已提交
1129 1130
				}
			});
1131 1132
		});
		request.on('error', (err) => {
1133
			reject(`Failed to query resource ${slug} with the following error: ${err}. ${options.path}`);
1134 1135
		});
		request.end();
1136
	}));
1137 1138
}

D
Dirk Baeumer 已提交
1139
export function prepareI18nFiles(): ThroughStream {
1140 1141
	let parsePromises: Promise<ParsedXLF[]>[] = [];

D
Dirk Baeumer 已提交
1142
	return through(function (this: ThroughStream, xlf: File) {
1143
		let stream = this;
1144 1145 1146
		let parsePromise = XLF.parse(xlf.contents.toString());
		parsePromises.push(parsePromise);
		parsePromise.then(
D
Dirk Baeumer 已提交
1147
			resolvedFiles => {
1148
				resolvedFiles.forEach(file => {
D
Dirk Baeumer 已提交
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
					let translatedFile = createI18nFile(file.originalFilePath, file.messages);
					stream.queue(translatedFile);
				});
			}
		);
	}, function () {
		Promise.all(parsePromises)
			.then(() => { this.queue(null); })
			.catch(reason => { throw new Error(reason); });
	});
}
1160

D
Dirk Baeumer 已提交
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
function createI18nFile(originalFilePath: string, messages: any): File {
	let result = Object.create(null);
	result[''] = [
		'--------------------------------------------------------------------------------------------',
		'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.'
	];
	for (let key of Object.keys(messages)) {
		result[key] = messages[key];
	}

D
Dirk Baeumer 已提交
1174 1175
	let content = JSON.stringify(result, null, '\t');
	if (process.platform === 'win32') {
D
Dirk Baeumer 已提交
1176
		content = content.replace(/\n/g, '\r\n');
D
Dirk Baeumer 已提交
1177
	}
D
Dirk Baeumer 已提交
1178 1179
	return new File({
		path: path.join(originalFilePath + '.i18n.json'),
1180
		contents: Buffer.from(content, 'utf8')
D
Dirk Baeumer 已提交
1181 1182
	});
}
1183

D
Dirk Baeumer 已提交
1184 1185 1186 1187 1188 1189 1190 1191 1192
interface I18nPack {
	version: string;
	contents: {
		[path: string]: Map<string>;
	};
}

const i18nPackVersion = "1.0.0";

1193 1194 1195 1196 1197 1198 1199
export interface TranslationPath {
	id: string;
	resourceName: string;
}

export function pullI18nPackFiles(apiHostname: string, username: string, password: string, language: Language, resultingTranslationPaths: TranslationPath[]): NodeJS.ReadableStream {
	return pullCoreAndExtensionsXlfFiles(apiHostname, username, password, language, externalExtensionsWithTranslations)
1200
		.pipe(prepareI18nPackFiles(externalExtensionsWithTranslations, resultingTranslationPaths, language.id === 'ps'));
D
Dirk Baeumer 已提交
1201 1202
}

1203
export function prepareI18nPackFiles(externalExtensions: Map<string>, resultingTranslationPaths: TranslationPath[], pseudo = false): NodeJS.ReadWriteStream {
D
Dirk Baeumer 已提交
1204 1205 1206 1207 1208
	let parsePromises: Promise<ParsedXLF[]>[] = [];
	let mainPack: I18nPack = { version: i18nPackVersion, contents: {} };
	let extensionsPacks: Map<I18nPack> = {};
	return through(function (this: ThroughStream, xlf: File) {
		let stream = this;
1209 1210
		let project = path.dirname(xlf.path);
		let resource = path.basename(xlf.path, '.xlf');
1211 1212
		let contents = xlf.contents.toString();
		let parsePromise = pseudo ? XLF.parsePseudo(contents) : XLF.parse(contents);
D
Dirk Baeumer 已提交
1213 1214 1215 1216 1217 1218
		parsePromises.push(parsePromise);
		parsePromise.then(
			resolvedFiles => {
				resolvedFiles.forEach(file => {
					const path = file.originalFilePath;
					const firstSlash = path.indexOf('/');
1219 1220 1221 1222 1223

					if (project === extensionsProject) {
						let extPack = extensionsPacks[resource];
						if (!extPack) {
							extPack = extensionsPacks[resource] = { version: i18nPackVersion, contents: {} };
D
Dirk Baeumer 已提交
1224
						}
1225 1226 1227 1228 1229 1230 1231
						const externalId = externalExtensions[resource];
						if (!externalId) { // internal extension: remove 'extensions/extensionId/' segnent
							const secondSlash = path.indexOf('/', firstSlash + 1);
							extPack.contents[path.substr(secondSlash + 1)] = file.messages;
						} else {
							extPack.contents[path] = file.messages;
						}
1232
					} else {
1233
						mainPack.contents[path.substr(firstSlash + 1)] = file.messages;
1234 1235 1236 1237
					}
				});
			}
		);
J
Joao Moreno 已提交
1238
	}, function () {
1239
		Promise.all(parsePromises)
D
Dirk Baeumer 已提交
1240 1241
			.then(() => {
				const translatedMainFile = createI18nFile('./main', mainPack);
1242 1243
				resultingTranslationPaths.push({ id: 'vscode', resourceName: 'main.i18n.json' });

D
Dirk Baeumer 已提交
1244 1245 1246 1247
				this.queue(translatedMainFile);
				for (let extension in extensionsPacks) {
					const translatedExtFile = createI18nFile(`./extensions/${extension}`, extensionsPacks[extension]);
					this.queue(translatedExtFile);
1248 1249 1250 1251 1252 1253 1254 1255

					const externalExtensionId = externalExtensions[extension];
					if (externalExtensionId) {
						resultingTranslationPaths.push({ id: externalExtensionId, resourceName: `extensions/${extension}.i18n.json` });
					} else {
						resultingTranslationPaths.push({ id: `vscode.${extension}`, resourceName: `extensions/${extension}.i18n.json` });
					}

D
Dirk Baeumer 已提交
1256 1257 1258
				}
				this.queue(null);
			})
1259
			.catch(reason => { throw new Error(reason); });
1260 1261 1262
	});
}

D
Dirk Baeumer 已提交
1263 1264
export function prepareIslFiles(language: Language, innoSetupConfig: InnoSetup): ThroughStream {
	let parsePromises: Promise<ParsedXLF[]>[] = [];
1265

D
Dirk Baeumer 已提交
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
	return through(function (this: ThroughStream, xlf: File) {
		let stream = this;
		let parsePromise = XLF.parse(xlf.contents.toString());
		parsePromises.push(parsePromise);
		parsePromise.then(
			resolvedFiles => {
				resolvedFiles.forEach(file => {
					if (path.basename(file.originalFilePath) === 'Default' && !innoSetupConfig.defaultInfo) {
						return;
					}
					let translatedFile = createIslFile(file.originalFilePath, file.messages, language, innoSetupConfig);
					stream.queue(translatedFile);
				});
			}
		);
	}, function () {
		Promise.all(parsePromises)
			.then(() => { this.queue(null); })
			.catch(reason => { throw new Error(reason); });
1285 1286 1287
	});
}

D
Dirk Baeumer 已提交
1288
function createIslFile(originalFilePath: string, messages: Map<string>, language: Language, innoSetup: InnoSetup): File {
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
	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 ***') {
1301
					content.push(`; *** Inno Setup version 5.5.3+ ${innoSetup.defaultInfo!.name} messages ***`);
1302 1303 1304 1305 1306 1307 1308 1309 1310
				} else {
					content.push(line);
				}
			} else {
				let sections: string[] = line.split('=');
				let key = sections[0];
				let translated = line;
				if (key) {
					if (key === 'LanguageName') {
1311
						translated = `${key}=${innoSetup.defaultInfo!.name}`;
1312
					} else if (key === 'LanguageID') {
1313
						translated = `${key}=${innoSetup.defaultInfo!.id}`;
1314
					} else if (key === 'LanguageCodePage') {
D
Dirk Baeumer 已提交
1315
						translated = `${key}=${innoSetup.codePage.substr(2)}`;
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
					} else {
						let translatedMessage = messages[key];
						if (translatedMessage) {
							translated = `${key}=${translatedMessage}`;
						}
					}
				}

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

1329
	const basename = path.basename(originalFilePath);
D
Dirk Baeumer 已提交
1330
	const filePath = `${basename}.${language.id}.isl`;
1331 1332 1333

	return new File({
		path: filePath,
1334
		contents: iconv.encode(Buffer.from(content.join('\r\n'), 'utf8'), innoSetup.codePage)
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
	});
}

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 已提交
1359
function decodeEntities(value: string): string {
1360
	return value.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
1361 1362 1363 1364
}

function pseudify(message: string) {
	return '\uFF3B' + message.replace(/[aouei]/g, '$&$&') + '\uFF3D';
D
Dirk Baeumer 已提交
1365
}