ast-function-call

Try in Playground
python-templatesUnknownInformational

0

template

No CWE or CVE

Raise an issue if we call logging.info with the argument foo.

Ast Rule: function call


ast-function-call

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 the analyzer did not get the arguments or if there is no argument, exit
  if(!node.arguments || !node.arguments.values || node.arguments.values.length  === 0) {
    return;
  }
  
  // moduleOrObject is what is shown before a method call
  // if you can logging.info, moduleOrObject is logging
  // if not defined or not logging we can exit
  if(!node.moduleOrObject || node.moduleOrObject.value !== "logging"){
    return;
  }
  
  // if the function is not defined or not equal to "info"
  // we can return.
  if(!node.functionName || node.functionName.value !== "info"){
    return;
  }
  
  
  // Get the list of argument
  const arguments = node.arguments.values;
  const nbArguments = node.arguments.values.length;
  
  // Get all the package list that are imported with "import <name>"
  const allPackages = node.getImports().filter(r => r.packages).flatMap(i => i.packages.map(p => p.name.str));
  
  // Do we use the logging package for Python?
  const useLoggingPackage = allPackages.filter(i => i === "logging").length > 0;
  if (!useLoggingPackage){
    return;
  }
  
  // Is the first argument value foo?
  const firstArgument = node.arguments.values[0];
  const isArgumentFoo = firstArgument.value.value === "foo";
  
  if(isArgumentFoo){
    // build the error
    const error = buildError(firstArgument.start.line, firstArgument.start.col, 
                             firstArgument.end.line, firstArgument.end.col, 
                             "do not use foo", "WARNING", "DESIGN");
    // build the fix (replace foo by bar)
    const edit = buildEditUpdate(firstArgument.start.line, firstArgument.start.col,
                                 firstArgument.end.line, firstArgument.end.col,
                                 "bar")
    // build a fix with one edit
    const fix = buildFix("replace with bar", [edit]);
    
    // report an error with a fix
    addError(error.addFix(fix));
  }
}
  

test-with-error.py

Expected test result: has error

import logging

logging.info(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.