fix-regex
Fixes a match by editing its text, instead of replacing it as a whole as fix does. The value is a mapping:
regex: a PCRE regular expression, run over the text of the match;replacement: the text that replaces each match of the regex.\1,\2and so on stand for the groups of the regex;count: the number of matches of the regex to replace, from the start. Without it, every match is replaced.
--autofix applies it, and opengrep test checks it against a .fixed file, as for fix.
Examples
Re-enabling TLS verification
tls-verify.yaml
rules: - id: tls-verify pattern: requests.$METHOD(..., verify=False, ...) fix-regex: regex: verify\s*=\s*False replacement: verify=True message: TLS certificate verification is disabled languages: [python] severity: WARNINGtls-verify.py
import requests# ruleid: tls-verifyrequests.get("https://api.example.com/users", verify = False)tls-verify.fixed.py
import requests# ruleid: tls-verifyrequests.get("https://api.example.com/users", verify=True)Command and result
$ opengrep test .
1/1: ✓ All tests passed
1/1: ✓ All fix tests passed Groups and count
rule.yaml
rules: - id: rename-all pattern: f(...) fix-regex: regex: (\d+) replacement: n\1 message: m languages: [python] severity: INFO - id: rename-first pattern: g(...) fix-regex: regex: (\d+) replacement: n\1 count: 1 message: m languages: [python] severity: INFOapp.py
f(1, 2, 3)g(1, 2, 3)Command and result
$ opengrep scan --config rule.yaml --autofix --dryrun app.py | grep 'fix:'
fix: f(n1, n2, n3)
fix: g(n1, 2, 3)