galactic-bot/language/LocaleLoader.js
2020-04-19 03:12:10 -07:00

71 lines
1.6 KiB
JavaScript

const path = require('path');
const fs = require('fs');
const { Util } = require('../util/');
class LocaleLoader {
constructor(client) {
this.client = client;
this.languages = {};
}
// directory = path.join(process.cwd(), 'languages', 'en_us')
async loadLanguage(language) {
const directory = path.join(process.cwd(), `language/languages/${language}`);
const files = Util.readdirRecursive(directory);
let combined = {};
for(let file of files) {
file = fs.readFileSync(file, {
encoding: 'utf8'
});
const result = this.loadFile(language, file);
Object.assign(combined, result);
}
this.languages[language] = combined;
console.log(this.languages);
}
loadFile(language, file) {
const lines = file.split('\n');
const parsed = {};
let matched = null;
let text = '';
for(const line of lines) {
const matches = line.match(/\[([_A-Z0-9]{1,})]/, 'gi');
if(matches) {
if(matched) {
parsed[matched] = text;
matched = matches[1];
text = '';
} else {
matched = matches[1];
}
} else {
if(matched) {
text += line;
} else {
continue;
}
}
}
if(matched) {
parsed[matched] = text;
}
return parsed;
}
}
module.exports = LocaleLoader;