index.js
2.25 KB
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
'use strict';
const execa = require('execa');
const lcid = require('lcid');
const mem = require('mem');
const defaultOpts = {spawn: true};
const defaultLocale = 'en_US';
function getEnvLocale(env) {
env = env || process.env;
return env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE;
}
function parseLocale(x) {
const env = x.split('\n').reduce((env, def) => {
def = def.split('=');
env[def[0]] = def[1].replace(/^"|"$/g, '');
return env;
}, {});
return getEnvLocale(env);
}
function getLocale(str) {
return (str && str.replace(/[.:].*/, ''));
}
function getAppleLocale() {
return execa.stdout('defaults', ['read', '-g', 'AppleLocale']);
}
function getAppleLocaleSync() {
return execa.sync('defaults', ['read', '-g', 'AppleLocale']).stdout;
}
function getUnixLocale() {
if (process.platform === 'darwin') {
return getAppleLocale();
}
return execa.stdout('locale')
.then(stdout => getLocale(parseLocale(stdout)));
}
function getUnixLocaleSync() {
if (process.platform === 'darwin') {
return getAppleLocaleSync();
}
return getLocale(parseLocale(execa.sync('locale').stdout));
}
function getWinLocale() {
return execa.stdout('wmic', ['os', 'get', 'locale'])
.then(stdout => {
const lcidCode = parseInt(stdout.replace('Locale', ''), 16);
return lcid.from(lcidCode);
});
}
function getWinLocaleSync() {
const stdout = execa.sync('wmic', ['os', 'get', 'locale']).stdout;
const lcidCode = parseInt(stdout.replace('Locale', ''), 16);
return lcid.from(lcidCode);
}
module.exports = mem(opts => {
opts = opts || defaultOpts;
const envLocale = getEnvLocale();
let thenable;
if (envLocale || opts.spawn === false) {
thenable = Promise.resolve(getLocale(envLocale));
} else if (process.platform === 'win32') {
thenable = getWinLocale();
} else {
thenable = getUnixLocale();
}
return thenable.then(locale => locale || defaultLocale)
.catch(() => defaultLocale);
});
module.exports.sync = mem(opts => {
opts = opts || defaultOpts;
const envLocale = getEnvLocale();
let res;
if (envLocale || opts.spawn === false) {
res = getLocale(envLocale);
} else {
try {
if (process.platform === 'win32') {
res = getWinLocaleSync();
} else {
res = getUnixLocaleSync();
}
} catch (err) {}
}
return res || defaultLocale;
});