galactic-bot/structure/language/LocaleLoader.js

88 lines
2.4 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/');
2020-04-19 12:12:10 +02:00
class LocaleLoader {
2020-04-19 12:12:10 +02:00
constructor(client) {
this.client = client;
this.languages = {};
2020-07-30 14:41:17 +02:00
2020-04-19 12:12:10 +02:00
}
template(locale, index) {
// console.log(String.raw`${this.languages[locale][index]}`);
2020-07-26 22:08:30 +02:00
return (this.languages[locale] ? this.languages[locale][index] : `Locale \`${locale}\` does not exist.`) || `Language entry \`${locale}:${index}\` does not exist.`;
}
async loadLanguages() {
const _directory = path.join(process.cwd(), 'structure/language/languages');
const directories = fs.readdirSync(_directory); //locale directories, ex. en_us, fi
for (const directory of directories) this.loadLanguage(directory);
}
loadLanguage(language) {
2020-04-19 12:12:10 +02:00
const directory = path.join(process.cwd(), `structure/language/languages/${language}`);
2020-04-19 12:12:10 +02:00
const files = Util.readdirRecursive(directory);
2020-05-24 11:00:54 +02:00
const combined = {};
2020-04-19 12:12:10 +02:00
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;
this.client.logger.info(`${chalk.bold('[LOCAL]')} Language ${chalk.bold(language)} was ${chalk.bold("loaded")}.`);
2020-04-19 12:12:10 +02:00
}
loadFile(file) {
2020-04-19 12:12:10 +02:00
2020-07-30 14:41:17 +02:00
if(process.platform === 'win32') {
file = file.split('\n').join('');
file = file.replace(/\r/gu, '\n');
}
2020-04-19 12:12:10 +02:00
const lines = file.split('\n');
const parsed = {};
let matched = null;
2020-07-30 14:41:17 +02:00
let text = [];
2020-04-19 12:12:10 +02:00
for(const line of lines) {
if(line.startsWith('//')) continue;
2020-05-24 10:54:33 +02:00
const matches = line.match(/\[([_A-Z0-9]{1,})\]/u);
2020-04-19 12:12:10 +02:00
if(matches) {
2020-05-24 11:00:54 +02:00
if (matched) {
2020-07-30 14:41:17 +02:00
parsed[matched] = text.join('\n').trim();
2020-05-24 11:00:54 +02:00
[, matched] = matches;
2020-07-30 14:41:17 +02:00
text = [];
2020-04-19 12:12:10 +02:00
} else {
2020-05-24 11:00:54 +02:00
[, matched] = matches;
2020-04-19 12:12:10 +02:00
}
2020-07-25 11:52:49 +02:00
} else if (matched) {
2020-07-30 14:41:17 +02:00
text.push(line);
2020-04-19 12:12:10 +02:00
} else {
2020-05-24 11:00:54 +02:00
continue;
2020-04-19 12:12:10 +02:00
}
}
2020-07-29 21:21:58 +02:00
2020-07-30 15:36:01 +02:00
parsed[matched] = text.join('\n').trim();
2020-04-19 12:12:10 +02:00
return parsed;
}
2020-07-30 14:41:17 +02:00
}
module.exports = LocaleLoader;