ban-module-import

Try in Playground
python-templatesUnknownInformational

0

No tags

No CWE or CVE

Template of a rule to ban some modules.

To update the rule and make it yours, update the PACKAGES_TO_BAN_WITH_REPLACEMENTS array. If you put null to the second value, nothing will be suggested.

Ast Rule: import


ban-module-import

How to write a rule
// ban the module foo
// we can two types of imports
//  - import foo
//  - from foo import bar


// name of the packages to ban with their replacements
const PACKAGES_TO_BAN_WITH_REPLACEMENTS = new Map([
  ['foo', 'bar'],
  ['python2', null],
]);


// Report the violation and build the fix
const reportFooPackageUsage = (node, replacement) => {
  const error = buildError(node.start.line, node.start.col, node.end.line, node.end.col, "Cannot import foo", "CRITICAL", "SAFETY");
  
  if (replacement) {
    const edit = buildEditUpdate(node.start.line, node.start.col,
                                 node.end.line, node.end.col,
                                 replacement);
  	const fix = buildFix(`use ${replacement}`, [edit]);
  	addError(error.addFix(fix));
  } else {
    addError(error);
  }
};


// Main function
function visit(node, filename, code) {
  for(const name of PACKAGES_TO_BAN_WITH_REPLACEMENTS.keys()) {
    // catch the code "from <package> import <something>"
    if (node.astType === "fromstatement" && node.pkg) {
      if (node.pkg && node.pkg.value === name) {
        reportFooPackageUsage(node.pkg, PACKAGES_TO_BAN_WITH_REPLACEMENTS.get(name));
      }
  	}
    
    // catch the code "import <something>"
    if (node.astType === "importstatement" && node.packages) {
      const importFoo = node.packages.filter(p => p.name.value === name);
      if(importFoo.length > 0) {
        reportFooPackageUsage(importFoo[0], PACKAGES_TO_BAN_WITH_REPLACEMENTS.get(name));
      }
    }
  }

}

python2-test.py

Expected test result: has error

import python2

import-check.py

Expected test result: has error

import foo

import-from-check.py

Expected test result: has error

from foo import 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.