Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@swernerx
Last active January 18, 2018 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swernerx/7a2b8f44b7cc250168f48e34cd07ad85 to your computer and use it in GitHub Desktop.
Save swernerx/7a2b8f44b7cc250168f48e34cd07ad85 to your computer and use it in GitHub Desktop.
Check translation files for spelling issues using the hunspell based "node-spellchecked"
#!/usr/bin/env node
const checker = require('spellchecker');
const chalk = require('chalk');
const glob = require('glob');
const root = require('app-root-dir').get();
const fs = require('fs-extra');
function check(word) {
if (checker.isMisspelled(word)) {
return checker.getCorrectionsForMisspelling(word);
}
return null;
}
function feedback(word) {
const result = check(word);
if (result === null) {
console.log(`- ${word}: ${chalk.green('okay')}`);
} else {
console.log(`- ${word}: ${chalk.red('error')}`);
if (result.length > 0) {
console.log(` Did you mean: ${result}?`);
}
}
}
function parseLanguage(filePath) {
return /_([a-zA-Z-]+)\.json$/.exec(filePath)[1];
}
function displayErrors(errors, key, translation) {
console.log(chalk.bold(' - ' + key + ': ' + errors.length + ' Errors'));
for (let {start, end} of errors) {
console.log(' - ' + translation.slice(start, end));
}
}
async function parseDict(dict) {
let json;
try {
json = await fs.readJson(dict);
} catch (error) {
throw new Error('Invalid JSON file: ' + dict);
}
const lang = parseLanguage(dict);
if (lang == null) {
throw new Error('Could not detect language of JSON file: ' + dict + '!');
}
checker.setDictionary(lang);
let errorCounter = 0;
for (let key in json) {
const translation = json[key];
const result = checker.checkSpelling(translation);
if (result.length > 0) {
if (errorCounter === 0) {
console.log(chalk.red('Errornous: ') + dict);
}
displayErrors(result, key, translation);
errorCounter += result.length;
}
}
if (errorCounter === 0) {
console.log(chalk.green('Perfect: ') + dict);
} else {
// Inject divider line
console.log('');
}
return errorCounter;
}
const ignore = ['**/node_modules/**'];
glob('**/src/**/translation*.json', {root, ignore}, async (error, matches) => {
const errors = await Promise.all(matches.map(parseDict));
const errorCount = errors.reduce((x, y) => x + y);
console.log("----------------------------------------------------------------------")
console.log(chalk.blue.bold('Overall Errors:', errorCount));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment