Merge pull request #444 from toasted-nutbread/unused-globals

Check for unused globals as part of CI
This commit is contained in:
toasted-nutbread 2020-04-13 18:55:19 -04:00 committed by GitHub
commit bf971be15b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 26 additions and 5 deletions

View File

@ -30,7 +30,6 @@
* Translator * Translator
* conditionsTestValue * conditionsTestValue
* dictConfigured * dictConfigured
* dictEnabledSet
* dictTermsSort * dictTermsSort
* handlebarsRenderDynamic * handlebarsRenderDynamic
* jp * jp

View File

@ -16,10 +16,7 @@
*/ */
/* global /* global
* JSZip
* JsonSchema
* dictFieldSplit * dictFieldSplit
* requestJson
*/ */
class Database { class Database {

View File

@ -37,6 +37,18 @@ function getNewline(string) {
} }
} }
function getSubstringCount(string, substring) {
let start = 0;
let count = 0;
while (true) {
const pos = string.indexOf(substring, start);
if (pos < 0) { break; }
++count;
start = pos + substring.length;
}
return count;
}
function validateGlobals(fileName, fix) { function validateGlobals(fileName, fix) {
const pattern = /\/\*\s*global\s+([\w\W]*?)\*\//g; const pattern = /\/\*\s*global\s+([\w\W]*?)\*\//g;
@ -47,6 +59,7 @@ function validateGlobals(fileName, fix) {
let first = true; let first = true;
let endIndex = 0; let endIndex = 0;
let newSource = ''; let newSource = '';
const allGlobals = [];
const newline = getNewline(source); const newline = getNewline(source);
while ((match = pattern.exec(source)) !== null) { while ((match = pattern.exec(source)) !== null) {
if (!first) { if (!first) {
@ -74,15 +87,27 @@ function validateGlobals(fileName, fix) {
newSource += source.substring(0, match.index); newSource += source.substring(0, match.index);
newSource += expected; newSource += expected;
endIndex = match.index + match[0].length; endIndex = match.index + match[0].length;
allGlobals.push(...parts);
} }
newSource += source.substring(endIndex); newSource += source.substring(endIndex);
// This is an approximate check to see if a global variable is unused.
// If the global appears in a comment, string, or similar, the check will pass.
let errorCount = 0;
for (const global of allGlobals) {
if (getSubstringCount(newSource, global) <= 1) {
console.error(`Global variable ${global} appears to be unused in ${fileName}`);
++errorCount;
}
}
if (fix) { if (fix) {
fs.writeFileSync(fileName, newSource, {encoding: 'utf8'}); fs.writeFileSync(fileName, newSource, {encoding: 'utf8'});
} }
return true; return errorCount === 0;
} }