forked from yola/gulp-static-i18n
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
100 lines (74 loc) · 2.14 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
'use strict';
var del = require('del');
var fs = require('fs');
var gutil = require('gulp-util');
var through = require('through2');
var vfs = require('vinyl-fs');
var transhbs = require('./lib/translators/handlebars');
var transjs = require('./lib/translators/javascript');
var transjson = require('./lib/translators/json');
var Translator = require('./lib/translator');
var PluginError = gutil.PluginError;
function StaticI18n(target, options, stream) {
this.target = target;
this.options = options || {};
this.stream = stream;
return this;
}
StaticI18n.prototype.translate = function(done) {
if(!this.checkTarget(this.target)){
done();
return;
}
var translator = new Translator(this.options);
var translate = translator.getStreamTranslator();
var targetPath = this.target.path;
var stage = this.target.path + '-stage';
var clearStage = function() {
del.sync(stage, {force: true});
};
var clearAndDone = function() {
clearStage();
done();
};
translator.register(['.js'], transjs);
translator.register(['.hbs'], transhbs);
translator.register(['.json'], transjson.configure(this.options));
clearStage();
fs.renameSync(targetPath, stage);
vfs.src(stage + '/**/*.*')
.pipe(translate)
.pipe(vfs.dest(targetPath))
.on('end', clearAndDone);
};
StaticI18n.prototype.error = function(msg) {
if (!this.stream) {
throw new Error(msg);
}
this.stream.emit('error', new PluginError('gulp-static-i18n', msg));
};
function isEmpty(dir) {
var items = fs.readdirSync(dir.path);
return !items || !items.length;
}
StaticI18n.prototype.checkTarget = function(dir) {
if (!dir || !dir.path || isEmpty(dir)) {
this.error('Missing files to translate.');
return false;
}
if (dir.isStream()) {
this.error('Streaming not supported');
return false;
}
return true;
};
// plugin wrapper so streams can pipe to it.
function gulpStaticI18n(options) {
return through.obj(function(target, encoding, cb) {
var stream = this;
var build = new StaticI18n(target, options, stream);
build.translate(cb);
});
}
module.exports = gulpStaticI18n;
module.exports.obj = StaticI18n;