galactic-bot/language/LocaleLoader.js

91 lines
2.5 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) {
// console.log(String.raw`${this.languages[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) this.loadLanguage(directory);
}
loadLanguage(language) {
2020-04-19 12:12:10 +02:00
const directory = path.join(process.cwd(), `language/languages/${language}`);
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(`Locale ${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-25 12:02:04 +02:00
if (process.platform === 'linux') file = file.replace('\r', '');
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) {
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-04-19 12:12:10 +02:00
parsed[matched] = text;
2020-05-24 11:00:54 +02:00
[, matched] = matches;
2020-04-19 12:12:10 +02:00
text = '';
} 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-05-24 11:00:54 +02:00
text += line;
2020-07-25 11:52:49 +02:00
if (process.platform === 'linux') text += '\n';
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
}
}
parsed[matched] = text;
2020-04-19 12:12:10 +02:00
2020-07-25 11:41:21 +02:00
if (process.platform === 'win32') for (const [key, value] of Object.entries(parsed)) {
2020-05-24 11:00:54 +02:00
parsed[key] = value.replace(/^(\r)|(\r){1,}$/gu, '').replace(/\r/gu, '\n');
2020-07-25 11:41:21 +02:00
// console.log(String.raw`${value}`);
2020-04-19 12:12:10 +02:00
}
2020-07-25 12:12:22 +02:00
//console.log(parsed);
2020-04-19 12:12:10 +02:00
return parsed;
}
}
module.exports = LocaleLoader;