Add conditions to rules to precisely target them


Last time we introduced custom rules into Sourcery.

This time they’re becoming even more powerful as you can filter pattern matches with a condition.

Let’s say we want to stop global variables being declared. First let’s write down what a global variable is:

  1. It’s declared at the top level of the module
  2. It’s not a constant using uppercase like DAYS_IN_WEEK = 7
  3. Let’s allow private globals starting with _

Here’s a rule to identify global variables:

rules:
    - id: no-global-variables
      pattern: ${var} = ${value}
      condition: |
          var.in_module_scope()
            and not var.is_upper_case()
            and not var.starts_with("_")
      description: Don't declare `${var}` as a global variable

Check out the conditions reference to see what conditions are available.

Added

Changed

Fixed