-
Notifications
You must be signed in to change notification settings - Fork 321
/
localize.ts
99 lines (88 loc) · 2.66 KB
/
localize.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
import * as fs from "fs";
import * as path from "path";
import { extensions } from "vscode";
interface IConfig {
locale?: string;
}
interface ILanguagePack {
[key: string]: string;
}
export class Localize {
// get language pack when the instance be created
private bundle = this.resolveLanguagePack();
constructor(private config: IConfig = {}) { }
/**
* translate the key
* @param key
* @param args
*/
public localize(key: string, ...args: any[]) {
const languagePack = this.bundle;
const message: string = languagePack[key] || key;
return this.format(message, args);
}
/**
* format the message
* @param message
* @param args
*/
private format(message: string, args: any[] = []): string {
let result: string;
if (args.length === 0) {
result = message;
} else {
result = message.replace(/\{(\d+)\}/g, (match, rest: any[]) => {
const index = rest[0];
return typeof args[index] !== "undefined" ? args[index] : match;
});
}
return result;
}
/**
* Get language pack
*/
private resolveLanguagePack(): ILanguagePack {
let resolvedLanguage: string = "";
const rootPath = extensions.getExtension("yzhang.markdown-all-in-one").extensionPath;
const file = path.join(rootPath, "package");
const options = this.config;
if (!options.locale) {
resolvedLanguage = ".nls.json";
} else {
let locale: string | null = options.locale;
while (locale) {
const candidate = ".nls." + locale + ".json";
if (fs.existsSync(file + candidate)) {
resolvedLanguage = candidate;
break;
} else {
const index = locale.lastIndexOf("-");
if (index > 0) {
locale = locale.substring(0, index);
} else {
resolvedLanguage = ".nls.json";
locale = null;
}
}
}
}
const languageFilePath = path.join(file + resolvedLanguage);
if (!fs.existsSync(languageFilePath)) {
return {};
}
return JSON.parse(fs.readFileSync(languageFilePath, "utf-8"));
}
}
let config: IConfig = {
locale: "en"
};
try {
config = Object.assign(
config,
JSON.parse((process.env as any).VSCODE_NLS_CONFIG)
);
} catch (err) {
//
}
const instance = new Localize(config);
export default instance.localize.bind(instance);