-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlang.js
93 lines (73 loc) · 2.45 KB
/
lang.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
const fs = require('fs');
const path = require('path');
const config = require('./config.js');
function getFilesInDirDeep(dir){
//console.log(`Looking into dir ${dir}`);
if(!fs.statSync(dir).isDirectory()){
console.log(`${dir} is not a directory`);
return [];
}
let items = fs.readdirSync(dir);
let files = items
.filter((item) => fs.statSync(path.join(dir, item)).isFile())
.map((filename) => path.join(dir, filename)); // Filename with dir
let directories = items.filter((item) => fs.statSync(path.join(dir, item)).isDirectory());
//console.log(`Found ${files.length} file(s) in ${dir}`);
directories.forEach((sub_dir) => {
files = files.concat(getFilesInDirDeep(path.join(dir, sub_dir)));
});
return files;
}
function getKeysInFiles(files, funcs){
const pattern = new RegExp('[^\w]('+funcs.join('|')+')\\(\\s*[\'"](.*?)[\'"]\\s*[\\),]', "g");
let keys = new Set();
let found = new Set();
for(let i = 0; files.length > i; i++){
let fileContent = fs.readFileSync(files[i], 'utf8');
let matches = null;
while(matches = pattern.exec(fileContent)){
keys.add(matches[2]);
// Also record in which files it was found
found.add(matches[2]);
if(!found[matches[2]]) found[matches[2]] = [];
found[matches[2]].push(files[i]);
};
}
return {keys: Array.from(keys), found} ;
}
function getLangs(dir){
if(!fs.statSync(dir).isDirectory()){
console.log(`${dir} is not a directory`);
return null;
}
let items = fs.readdirSync(dir);
let jsonFiles = items.filter((filename) => {
return fs.statSync(path.join(dir, filename)).isFile() && filename.endsWith('.json');
});
let lang = {};
jsonFiles.forEach((filename) => {
lang[filename.substr(0, filename.indexOf('.'))] = require(path.join(dir, filename));
});
return lang;
}
function writeLangFile(file, json){
let sortedObject = {};
if(config.get('sortKeysOnSave')){
Object.keys(json)
.sort()
.forEach(function(v, i) {
sortedObject[v] = json[v];
});
}
else{
sortedObject = json;
}
const indentation = " ".repeat(config.get('saveIndentation'));
return new Promise((resolve, reject) => {
fs.writeFile(file, JSON.stringify(sortedObject, null, indentation), function(err) {
if(err) reject(err);
else resolve(file);
});
});
}
module.exports = { getLangs, getKeysInFiles, getFilesInDirDeep, writeLangFile };