pattern-rule

Try in Playground
python-templatesBest PracticeInformational

0

template

No CWE or CVE

Simple pattern test with one variable and one fix

Pattern Rule: open(${file})


pattern-rule

How to write a rule
function visit(pattern, filename, code) {

  // If filename starts or ends with test_ or _test, do not do anything
  if(filename.includes("_test.py") || filename.startsWith("test_")) {
    return;
  }
  
  const fileVariable = pattern.variables.get("file");
  const modeVariable = pattern.variables.get("mode");
  
  const fileVariableTextValue = fileVariable.value;
  
  console.log(fileVariableTextValue);
  
  // If the name of the variable passed is foo, raise an error
  if (fileVariableTextValue === "foo") {
    // build the error being reported
    const error = buildError(pattern.start.line, pattern.start.col, pattern.end.line, pattern.end.col, "Do not use foo as a variable", "INFO", "BEST_PRACTICES");
    
    // Make an edit to replace where the variable is by "bar"
    const edit = buildEdit(fileVariable.start.line, fileVariable.start.col, fileVariable.end.line, fileVariable.end.col, "update", "bar");
    
    // Make a fix with the edit we previously built
    const fix = buildFix("use bar instead", [edit]);
    
    // add the error to the list of reported errors
    addError(error.addFix(fix));
  }

}

success-test.py

Expected test result: no error

v = open(foo)

failing-test.py

Expected test result: has error

v = open(bar)
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.