if-condition

Try in Playground
python-templatesUnknownInformational

0

template

No CWE or CVE

Ast Rule: if condition


if-condition

How to write a rule
function visit(node, filename, code) {
  // If filename starts or ends with test_ or _test, do not do anything
  if(filename.includes("_test.py") || filename.startsWith("test_")) {
    return;
  }
  
  // if we fail to get the condition, return
  if (!node.condition) {
    return;
  }
  
  if (!node.condition.rightSide || !node.condition.rightSide.expression) {
    return;
  }
  
  // Get the right side of the condition
  const rightSide = node.condition.rightSide;
  
  // if the right side is an atom and equal to True, report an error
  if(rightSide.expression.atom && rightSide.expression.atom.str === "True"){
    // report the error on the condition
    const error = buildError(node.condition.start.line, node.condition.start.col, node.condition.end.line, node.condition.end.col, "do not make equal with true", "INFO", "BEST_PRACTICE");

    // Replace the complete condition with just the left side
    const editReplaceCondition = buildEditUpdate(node.condition.start.line, node.condition.start.col, 
                                                 node.condition.rightSide.expression.atom.end.line, 
                                                 node.condition.rightSide.expression.atom.end.col, 
                                                 node.condition.leftSide.getText())


    // build a fix with the error
    const fix = buildFix("remove True", [editReplaceCondition]);
    addError(error.addFix(fix));
  }
}

no-if-true

Expected test result: has error

if foo:
  print("bar")
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
Legal
  • Security
  • Privacy Policy
  • Code Privacy
  • Terms of Service
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.