variable-name

Try in Playground
python-inclusiveBest PracticeInformational

0

No tags

No CWE or CVE

This rule checks that the variable names do not use certain words (such as master or slave) and suggest better alternatives.

Ast Rule: assignment


variable-name

How to write a rule
const NAMES_TO_REPLACE = new Map([
  ['blacklist', 'denylist'],
  ['whitelist', 'allowlist'],
  ['master', 'primary'],
  ['slave', 'secondary'],
  ['dummy', 'placeholder'],
]);


const checkString = (node, avoidString, replaceString) => {
  if(node && node.value && node.value.includes(avoidString)) {
    const updatedName = node.value.replace(avoidString, replaceString);
    const error = buildError(node.start.line, node.start.col, 
                             node.end.line, node.end.col, 
                             `do not use word ${avoidString}`, "INFO", "BEST_PRACTICES");
    const edit = buildEditUpdate(node.start.line, node.start.col,
                                 node.end.line, node.end.col,
                                 updatedName);
    const fix = buildFix(`use ${updatedName} instead`, [edit]);
    addError(error.addFix(fix));
  }
}


function visit(node, filename, code) {
	if(!node.left) {
    return;
  }

  for (const name of NAMES_TO_REPLACE.keys()) {
    const replacement = NAMES_TO_REPLACE.get(name);
    if(node.left.astType === "string") {
      checkString(node.left, name, replacement);
    }
    if(node.left.astType === "list") {
      if(node.left.elements) {
        node.left.elements.forEach(element => {
          if(element.astType === "string"){
            checkString(element, name, replacement);
          }
        });
      }
    }
  }
}

test-list.py

Expected test result: no error

blacklist_foo, whitelist_bar = foo()

test-variable.py

Expected test result: has error

blacklist_something = foo()
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Explore
  • Cookbooks
  • Playground
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.