Skip to content

Commit

Permalink
Exclude invalid translations from json (#3434)
Browse files Browse the repository at this point in the history
  • Loading branch information
tomaskikutis authored Apr 16, 2020
1 parent f334f6f commit 94ae4a9
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions tasks/compile-translations-po-to-json.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,56 @@ function isDirectory(path) {
}
}

/*
It iterates all user supplied translations and removes placeholders found in the original string.
If there are any additional placeholders left, the translation is considered invalid. It is whitespace sensitive.
For example: `{"Update {{sequence}}": "Mettre à jour {{séquence}}"}`
The original placeholder is `{{sequence}}`. It would be removed from the translation, but it doesn't contain it.
An additional placeholder that was not in the original string is found - `{{séquence}}` and because of this
the translation is considered invalid and will not be outputted to JSON.
*/

function removeInvalidTranslations(grunt, jsonFilePath, filename) {
var translations = JSON.parse(fs.readFileSync(jsonFilePath, 'utf8'));

const validTranslations = Object.keys(translations).filter((key) => {
if (key === '') { // metadata object added by gettext.js
return true;
}

const placeHolders = key.match(/{{.+?}}/g);

return (Array.isArray(translations[key]) ? translations[key] : [translations[key]]).every(
(translatedString) => {
const translatedStringWithoutPlaceholders = (placeHolders || []).reduce((acc, item) => {
return acc.replace(item, '');
}, translatedString);

const valid = translatedStringWithoutPlaceholders.match(/{{.+?}}/) == null;

if (valid !== true) {
grunt.log.error(
`Invalid translation string encountered in "${filename}"`
+ ` and will be ommited from JSON: "${translatedString}"`
);
}

return valid;
}
);
}).reduce((acc, key) => {
acc[key] = translations[key];

return acc;
}, {});

fs.writeFileSync(jsonFilePath, JSON.stringify(validTranslations), 'utf8');
}

function compileTranslationsPoToJson(grunt) {
const currentDir = process.cwd();
const clientCoreRoot = path.join(__dirname, '../');
Expand Down Expand Up @@ -41,6 +91,8 @@ function compileTranslationsPoToJson(grunt) {
`${po2json} ${poFile} ${jsonFile}`,
{stdio: 'inherit'}
);

removeInvalidTranslations(grunt, jsonFile, filename);
});
}

Expand Down

0 comments on commit 94ae4a9

Please sign in to comment.