What are Custom Rules?
Let’s say your codebase has specific and repetitive coding issues that you want to address. You use the built-in rules of Salesforce Code Analyzer (Code Analyzer) to find these rule violations. But sometimes the problems exist only in the context of your codebase, and sometimes Code Analyzer’s built-in rules don’t catch them. In this case, create your own custom rules to highlight these issues as rule violations when you scan your code.
Because PMD and ESLint custom rules work differently, Code Analyzer deals with each in distinct ways.
PMD Custom Rules
Write PMD Custom Rules
To be compatible with Code Analyzer, build your PMD custom rules following these guidelines:
- Declare your new XPath or Java-based rules in custom category XML files using this format:
<some base dir>/category/<language>/<filename>.xml. For more info, read PMD’s XML rule definition documentation.
- Combine your custom rules and PMD’s built-in rules into custom rulesets in XML files using this format:
<some base dir>/rulesets/<language>/<filename>.xml. For more info, read PMD’s Making rulesets.
- Register custom rulesets or XPath-only custom categories with Code Analyzer as standalone XML files.
- Compile your Java-based rules, and bundle them into a JAR along with your rule declaration files, then register that JAR with Code Analyzer. We recommend using a build tool such as Maven or Gradle to manage the dependency on PMD and automate the process of building the JAR. Use our example repo as a scaffold to build your own project.
Refer to Managing Custom Rules for information about how to register and run your custom PMD rules.
- PMD Source Code Analyzer Project: Introduction to writing PMD rules
- PMD Source Code Analyzer Project: XML rule definition
ESLint Custom Rules
Write ESLint Custom Rules
Writing custom ESLint rules requires creating a custom ESLint plug-in and defining rules within it. For help with writing ESLint rules, refer to ESLint’s Working with Rules documentation.
Add Rules as an npm Dependency
ESLint rule definitions must contain documentation. Format your documentation like this:
// Rule definition in index.js or where you choose to store it
description: "Information about the rule"
After your rule is ready and tested, add it as a dependency to the
npm setup in the same directory where Code Analyzer runs. Use the
yarn version of this command.
yarn add file:/path/to/ESLint-plugin-my-custom
npm install file:/path/to/ESLint-plugin-my-custom
After your rule is added, ensure that the
- Has a child directory with your plug-in’s name.
- Contains the
index.jsand other files that you created.