This repository has been archived by the owner on Jun 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
84 lines (66 loc) · 1.82 KB
/
index.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
var path = require('path');
var gutil = require('gulp-util'),
merge = require('merge'),
through = require('through2'),
YAML = require('yamljs'),
File = gutil.File;
const NAME = 'gulp-localize';
const REG = /\{{2}\s?(\w[-\w\.]*)\s?\}{2}/g;
const LOC = /\{{2}\s?\}{2}/g;
function err(msg) {
return new gutil.PluginError(NAME, msg);
}
module.exports = function(opt){
var options = merge({
locales: ['en', 'it'],
path: 'locale'
}, opt);
var locales = {};
options.locales.forEach(function(locale){
locales[locale] = YAML.load(options.path + '/' + locale + '.yml');
});
function get(key, locale) {
return key.split('.').reduce(function(obj, key) {
return (obj && key in obj) ? obj[key] : null;
}, locales[locale]);
}
function transform(file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
this.emit('error', err('Streaming not supported'));
return cb();
}
var text = file.contents.toString(enc),
key,
length,
locale,
match,
result,
string;
for (locale in locales) {
result = text.replace(LOC, locale);
while ((match = REG.exec(result)) !== null) {
key = match[1].trim();
string = get(key, locale);
if (string === null) {
this.emit('error', err('Cannot find key "' + key + '" in locale ' + locale));
return cb();
}
length = result.length;
result = result.replace(match[0], string);
REG.lastIndex += result.length - length;
}
this.push(new File({
cwd: file.cwd,
base: file.base,
path: path.join(file.base, locale, file.relative),
contents: new Buffer(result)
}));
}
cb();
}
return through.obj(transform);
};