galactic-bot/language/LocaleLoader.js

86 lines
2.1 KiB
JavaScript
Raw Normal View History

2020-04-19 12:12:10 +02:00
const path = require('path');
const fs = require('fs');
const chalk = require('chalk');
2020-04-19 12:12:10 +02:00
const { Util } = require('../util/');
class LocaleLoader {
2020-04-19 12:12:10 +02:00
constructor(client) {
this.client = client;
this.languages = {};
}
template(locale, index) {
return this.languages[locale] ? this.languages[locale][index] : `Locale ${locale} does not exist.` || `Entry ${locale}:${index} does not exist.`;
}
async loadLanguages() {
const _directory = path.join(process.cwd(), 'language/languages');
const directories = fs.readdirSync(_directory); //locale directories, ex. en_us, fi
for (const directory of directories) await this.loadLanguage(directory);
}
2020-04-19 12:12:10 +02:00
async loadLanguage(language) {
this.client.logger.info(`Loading locale ${chalk.bold(language)}`);
2020-04-19 12:12:10 +02:00
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(file);
2020-04-19 12:12:10 +02:00
Object.assign(combined, result);
}
this.languages[language] = combined;
}
loadFile(file) {
2020-04-19 12:12:10 +02:00
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;