format-string

Try in Playground
julien-pythonUnknownInformational

0

No tags

No CWE or CVE

Ast Rule: function call


format-string

How to write a rule
function visit(node, filename, code) {
  if (node.functionName.value !== "format"){
    return;
  }
  if (!node.moduleOrObject || !node.moduleOrObject.value || !node.arguments || !node.arguments.values){
    return;
  }
  var newText = node.moduleOrObject.value;
  const arguments = node.arguments.values.map(a => {
    return a.value.str;
  });
  
  for(var i = 0; i < arguments.length ; i = i + 1) {
    const v = arguments[i];
    const isString = v.startsWith('"') && v.length > 2 && v.endsWith('"');
    
    if (isString) {
      // remove the quotes
      const s = v.substring(1, v.length - 1);
      newText = newText.replaceAll(`{${i}}`, s);
    } else {
      newText = newText.replaceAll(`{${i}}`,`{${arguments[i]}}`);
    }
    
  }
    
  const newValue = `f${newText}`;
  const error = buildError(node.start.line, node.start.col, node.end.line, node.end.col, "Format string are old format", "INFO", "BEST_PRACTICES");
  const edit = buildEdit(node.start.line, node.start.col, node.end.line, node.end.col, "update", newValue);
  const fix = buildFix("replace with f-string", [edit]);
  addError(error.addFix(fix));
    
}
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.