|
1 | 1 | from abc import ABCMeta
|
2 | 2 | from abc import abstractmethod
|
| 3 | +from abc import abstractproperty |
3 | 4 |
|
| 5 | +from detect_secrets.core.potential_secret import PotentialSecret |
4 | 6 | from detect_secrets.plugins.core.constants import WHITELIST_REGEX
|
5 | 7 |
|
6 | 8 |
|
@@ -83,3 +85,46 @@ def __dict__(self):
|
83 | 85 | return {
|
84 | 86 | 'name': self.__class__.__name__,
|
85 | 87 | }
|
| 88 | + |
| 89 | + |
| 90 | +class RegexBasedDetector(BasePlugin): |
| 91 | + """Base class for regular-expressed based detectors. |
| 92 | +
|
| 93 | + To create a new regex-based detector, subclass this and set |
| 94 | + `secret_type` with a description and `blacklist` |
| 95 | + with a sequence of regular expressions, like: |
| 96 | +
|
| 97 | + class FooDetector(RegexBasedDetector): |
| 98 | + secret_type = "foo" |
| 99 | + blacklist = ( |
| 100 | + re.compile(r'foo'), |
| 101 | + ) |
| 102 | + """ |
| 103 | + __metaclass__ = ABCMeta |
| 104 | + |
| 105 | + @abstractproperty |
| 106 | + def secret_type(self): |
| 107 | + return NotImplementedError |
| 108 | + |
| 109 | + @abstractproperty |
| 110 | + def blacklist(self): |
| 111 | + return NotImplementedError |
| 112 | + |
| 113 | + def analyze_string(self, string, line_num, filename): |
| 114 | + output = {} |
| 115 | + |
| 116 | + for identifier in self.secret_generator(string): |
| 117 | + secret = PotentialSecret( |
| 118 | + self.secret_type, |
| 119 | + filename, |
| 120 | + identifier, |
| 121 | + line_num, |
| 122 | + ) |
| 123 | + output[secret] = secret |
| 124 | + |
| 125 | + return output |
| 126 | + |
| 127 | + def secret_generator(self, string): |
| 128 | + for regex in self.blacklist: |
| 129 | + if regex.search(string): |
| 130 | + yield regex.pattern |
0 commit comments