This repository has been archived by the owner on Aug 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgettext.js
95 lines (80 loc) · 2.25 KB
/
gettext.js
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
/**
* Module dependencies
*/
var util = require('util')
, path = require('path');
/**
* Look up a string by name, using environment variable
* to detect the appropriate locale.
* If a stringfile doesn't exist, default to `en`.
*
* @api experimental
*
* @address {String} keypath [e.g. 'cli.new.successful']
* @address {Object} args [ordered scope args for `util.format()`]
* @return {String}
*/
module.exports = function getString (keypath, args) {
var locale =
process.env.LANGUAGE ||
process.env.LC_ALL ||
process.env.LC_MESSAGES ||
process.env.LANG ||
'en';
locale = locale.toLowerCase();
// Just to be safe, check that there are no '/'
// (in case an attacker attempts to use environment
// variables to load malicious code)
if (locale.match(/[\/]+/)) return util.format('INVALID LOCALE: %s',locale);
// TODO: do something smarter here to determine the proper stringfile
if (locale.match('en')) {
locale = 'en';
}
var stringfile, pathToLocale;
try {
pathToLocale = path.resolve(__dirname, './locales/',locale);
stringfile = require( pathToLocale );
}
catch(e) {
// In the event of an unresolvable locale,
// fail silently and default to english
pathToLocale = path.resolve(__dirname, './locales/en');
stringfile = require( pathToLocale );
// return util.format(
// 'ERROR LOADING LOCALE: '+
// 'Unable to find stringfile for locale `%s`',
// locale);
}
var strtemplate = _deepValue(stringfile, keypath);
if (!strtemplate) return util.format('STRING `%s` NOT DEFINED IN `%s` LOCALE!',keypath, locale);
return util.format.apply( null, [strtemplate].concat(args || []));
};
/**
* @api private
*
* Lookup a value in an object given a keypath.
*
* @param {Object} object [description]
* @param {String} path [description]
* @return {[type]} [description]
*/
function _deepValue (object, path) {
if ('undefined' == typeof object || object === null) {
return null;
}
var val = object;
path = path.split('.');
while (path.length) {
var part = path.shift();
if ('undefined' == typeof val[part]) {
return null;
} else {
val = val[part];
}
}
// Try [0] if an object remains
if (typeof val === 'object') {
if (typeof val[0] === 'string') val = val[0];
}
return val;
}