-
Notifications
You must be signed in to change notification settings - Fork 31.9k
/
Copy pathnls.ts
233 lines (195 loc) · 7.58 KB
/
nls.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/*---------------------------------------------------------------------------------------------
* 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';
import * as perf from '../common/performance.js';
import type { ILanguagePacks, INLSConfiguration } from '../../nls.js';
export interface IResolveNLSConfigurationContext {
/**
* Location where `nls.messages.json` and `nls.keys.json` are stored.
*/
readonly nlsMetadataPath: string;
/**
* Path to the user data directory. Used as a cache for
* language packs converted to the format we need.
*/
readonly userDataPath: string;
/**
* Commit of the running application. Can be `undefined`
* when not built.
*/
readonly commit: string | undefined;
/**
* Locale as defined in `argv.json` or `app.getLocale()`.
*/
readonly userLocale: string;
/**
* Locale as defined by the OS (e.g. `app.getPreferredSystemLanguages()`).
*/
readonly osLocale: string;
}
export async function resolveNLSConfiguration({ userLocale, osLocale, userDataPath, commit, nlsMetadataPath }: IResolveNLSConfigurationContext): Promise<INLSConfiguration> {
perf.mark('code/willGenerateNls');
if (
process.env['VSCODE_DEV'] ||
userLocale === 'pseudo' ||
userLocale.startsWith('en') ||
!commit ||
!userDataPath
) {
return defaultNLSConfiguration(userLocale, osLocale, nlsMetadataPath);
}
try {
const languagePacks = await getLanguagePackConfigurations(userDataPath);
if (!languagePacks) {
return defaultNLSConfiguration(userLocale, osLocale, nlsMetadataPath);
}
const resolvedLanguage = resolveLanguagePackLanguage(languagePacks, userLocale);
if (!resolvedLanguage) {
return defaultNLSConfiguration(userLocale, osLocale, nlsMetadataPath);
}
const languagePack = languagePacks[resolvedLanguage];
const mainLanguagePackPath = languagePack?.translations?.['vscode'];
if (
!languagePack ||
typeof languagePack.hash !== 'string' ||
!languagePack.translations ||
typeof mainLanguagePackPath !== 'string' ||
!(await exists(mainLanguagePackPath))
) {
return defaultNLSConfiguration(userLocale, osLocale, nlsMetadataPath);
}
const languagePackId = `${languagePack.hash}.${resolvedLanguage}`;
const globalLanguagePackCachePath = path.join(userDataPath, 'clp', languagePackId);
const commitLanguagePackCachePath = path.join(globalLanguagePackCachePath, commit);
const languagePackMessagesFile = path.join(commitLanguagePackCachePath, 'nls.messages.json');
const translationsConfigFile = path.join(globalLanguagePackCachePath, 'tcf.json');
const languagePackCorruptMarkerFile = path.join(globalLanguagePackCachePath, 'corrupted.info');
if (await exists(languagePackCorruptMarkerFile)) {
await fs.promises.rm(globalLanguagePackCachePath, { recursive: true, force: true, maxRetries: 3 }); // delete corrupted cache folder
}
const result: INLSConfiguration = {
userLocale,
osLocale,
resolvedLanguage,
defaultMessagesFile: path.join(nlsMetadataPath, 'nls.messages.json'),
languagePack: {
translationsConfigFile,
messagesFile: languagePackMessagesFile,
corruptMarkerFile: languagePackCorruptMarkerFile
},
// NLS: below properties are a relic from old times only used by vscode-nls and deprecated
locale: userLocale,
availableLanguages: { '*': resolvedLanguage },
_languagePackId: languagePackId,
_languagePackSupport: true,
_translationsConfigFile: translationsConfigFile,
_cacheRoot: globalLanguagePackCachePath,
_resolvedLanguagePackCoreLocation: commitLanguagePackCachePath,
_corruptedFile: languagePackCorruptMarkerFile
};
if (await exists(commitLanguagePackCachePath)) {
touch(commitLanguagePackCachePath).catch(() => { }); // We don't wait for this. No big harm if we can't touch
perf.mark('code/didGenerateNls');
return result;
}
const [
,
nlsDefaultKeys,
nlsDefaultMessages,
nlsPackdata
]:
[unknown, Array<[string, string[]]>, string[], { contents: Record<string, Record<string, string>> }]
// ^moduleId ^nlsKeys ^moduleId ^nlsKey ^nlsValue
= await Promise.all([
fs.promises.mkdir(commitLanguagePackCachePath, { recursive: true }),
fs.promises.readFile(path.join(nlsMetadataPath, 'nls.keys.json'), 'utf-8').then(content => JSON.parse(content)),
fs.promises.readFile(path.join(nlsMetadataPath, 'nls.messages.json'), 'utf-8').then(content => JSON.parse(content)),
fs.promises.readFile(mainLanguagePackPath, 'utf-8').then(content => JSON.parse(content)),
]);
const nlsResult: string[] = [];
// We expect NLS messages to be in a flat array in sorted order as they
// where produced during build time. We use `nls.keys.json` to know the
// right order and then lookup the related message from the translation.
// If a translation does not exist, we fallback to the default message.
let nlsIndex = 0;
for (const [moduleId, nlsKeys] of nlsDefaultKeys) {
const moduleTranslations = nlsPackdata.contents[moduleId];
for (const nlsKey of nlsKeys) {
nlsResult.push(moduleTranslations?.[nlsKey] || nlsDefaultMessages[nlsIndex]);
nlsIndex++;
}
}
await Promise.all([
fs.promises.writeFile(languagePackMessagesFile, JSON.stringify(nlsResult), 'utf-8'),
fs.promises.writeFile(translationsConfigFile, JSON.stringify(languagePack.translations), 'utf-8')
]);
perf.mark('code/didGenerateNls');
return result;
} catch (error) {
console.error('Generating translation files failed.', error);
}
return defaultNLSConfiguration(userLocale, osLocale, nlsMetadataPath);
}
/**
* The `languagepacks.json` file is a JSON file that contains all metadata
* about installed language extensions per language. Specifically, for
* core (`vscode`) and all extensions it supports, it points to the related
* translation files.
*
* The file is updated whenever a new language pack is installed or removed.
*/
async function getLanguagePackConfigurations(userDataPath: string): Promise<ILanguagePacks | undefined> {
const configFile = path.join(userDataPath, 'languagepacks.json');
try {
return JSON.parse(await fs.promises.readFile(configFile, 'utf-8'));
} catch (err) {
return undefined; // Do nothing. If we can't read the file we have no language pack config.
}
}
function resolveLanguagePackLanguage(languagePacks: ILanguagePacks, locale: string | undefined): string | undefined {
try {
while (locale) {
if (languagePacks[locale]) {
return locale;
}
const index = locale.lastIndexOf('-');
if (index > 0) {
locale = locale.substring(0, index);
} else {
return undefined;
}
}
} catch (error) {
console.error('Resolving language pack configuration failed.', error);
}
return undefined;
}
function defaultNLSConfiguration(userLocale: string, osLocale: string, nlsMetadataPath: string): INLSConfiguration {
perf.mark('code/didGenerateNls');
return {
userLocale,
osLocale,
resolvedLanguage: 'en',
defaultMessagesFile: path.join(nlsMetadataPath, 'nls.messages.json'),
// NLS: below 2 are a relic from old times only used by vscode-nls and deprecated
locale: userLocale,
availableLanguages: {}
};
}
//#region fs helpers
async function exists(path: string): Promise<boolean> {
try {
await fs.promises.access(path);
return true;
} catch {
return false;
}
}
function touch(path: string): Promise<void> {
const date = new Date();
return fs.promises.utimes(path, date, date);
}
//#endregion