-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
92 lines (83 loc) · 3.61 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
'use strict';
var through = require('through2');
var parse = require('csv-parse');
var gUtil = require('gulp-util');
var path = require('path');
// consts
var PLUGIN_NAME = 'gulp-csv-angular-translate';
module.exports = function(options) {
var readCsvAndCreateJsonFiles = function(file, enc, callback) {
//check if file is null
if (file.isNull()) {
console.log("gulp-csv-angular-translate: FILE IS NULL");
return callback(null, file);
}
//check if file is steam
if (file.isStream()) {
console.log("gulp-csv-angular-translate: FILE IS STREAM");
return callback(null, file);
}
//check if file is buffer
if (file.isBuffer()) {
var csvText = file.contents;
var fileEnding = '.json';
var sthis = this;
//parseOptions
var parseOptions;
if (options && options.csvParseOptions) {
parseOptions = options.csvParseOptions;
} else {
parseOptions = {comment: '#'};
}
var skipEmptyTranslations = false;
if (options && options.skipEmptyTranslations) {
skipEmptyTranslations = true;
}
parse(csvText, parseOptions, function(err, output) {
if (err) {
console.error('gulp-csv-angular-translate: COULD NOT PARSE CSV FILE [ERROR: '+err+']');
} else {
var files = [];
//iterate over rows
for (var row=0; row<output.length; row++) {
var duplicateErrorPrinted = false;
//iterate over columns
for (var column=1; column<output[row].length; column++) {
if (row===0) {
//initialize the files with file names from the header row
files.push({langName: output[0][column], fileContent: {}});
} else {
//check if translation key is duplicate
if (files[column - 1] && files[column - 1].fileContent[output[row][0]] && !duplicateErrorPrinted) {
console.warn('gulp-csv-angular-translate: FOUND DUPLICATE TRANSLATION-KEY ['+output[row][0]+']');
duplicateErrorPrinted = true;
}
if (output[row][column] || !skipEmptyTranslations) {
files[column - 1].fileContent[output[row][0]] = output[row][column];
}
}
}
}
//create and push files
for (var file=0; file<files.length; file++) {
//create file
var tempFile = new gUtil.File({
base: '.',
cwd: __dirname,
path: files[file].langName+fileEnding
});
//JS Object -> JSON
var content = JSON.stringify(files[file].fileContent);
//set file content
tempFile.contents = new Buffer(content);
//push file
sthis.push(tempFile);
}
}
});
}
//drop input file
callback(null);
};
return through.obj(readCsvAndCreateJsonFiles);
};