把[{'name':str, 'params':str}...]格式的rule_list转换为 rule_name-value的格式,并把reg_exp编译好 :param rule_list: [{'name':str, 'params':str}...] :return: { rule_name: { 'reg_pattern': reg_pattern, 'exclude': exclude_paths, 'include': inclu
(self, rule_list)
| 140 | |
| 141 | class RegexScan(CodeLintModel): |
| 142 | def __format_rules(self, rule_list): |
| 143 | """把[{'name':str, 'params':str}...]格式的rule_list转换为 rule_name-value的格式,并把reg_exp编译好 |
| 144 | :param rule_list: [{'name':str, 'params':str}...] |
| 145 | :return: { |
| 146 | rule_name: { |
| 147 | 'reg_pattern': reg_pattern, |
| 148 | 'exclude': exclude_paths, |
| 149 | 'include': include_paths, |
| 150 | 'msg': msg, |
| 151 | 'ignore_comment': True|False |
| 152 | } |
| 153 | } |
| 154 | """ |
| 155 | rules = {} |
| 156 | for rule in rule_list: |
| 157 | rule_name = rule['name'] |
| 158 | if not rule.get('params'): |
| 159 | logger.error(f"{rule_name} rule parameter is empty, check for existing rules.") |
| 160 | continue |
| 161 | if "[regexcheck]" in rule['params']: |
| 162 | rule_params = rule['params'] |
| 163 | else: |
| 164 | rule_params = "[regexcheck]\r\n" + rule['params'] |
| 165 | rule_params_dict = ConfigReader(cfg_string=rule_params).read('regexcheck') |
| 166 | |
| 167 | reg_exp = rule_params_dict.get('regex', '') |
| 168 | if not reg_exp: |
| 169 | logger.error(f"{rule_name} rule parameter is wrong, not fill in the regular expression, skip this rule.") |
| 170 | continue |
| 171 | reg_pattern = re.compile(reg_exp) |
| 172 | exclude_paths = rule_params_dict.get('exclude', '') |
| 173 | exclude_paths = [p.strip() for p in exclude_paths.split(';') if p.strip()] if exclude_paths else [] |
| 174 | include_paths = rule_params_dict.get('include', '') |
| 175 | include_paths = [p.strip() for p in include_paths.split(';') if p.strip()] if include_paths else [] |
| 176 | # 大小写不敏感,可以支持True|true|False|false等 |
| 177 | ignore_comment = True if rule_params_dict.get('ignore_comment', 'False').lower() == 'true' else False |
| 178 | msg = rule_params_dict.get('msg', "Irregular codes found: %s") |
| 179 | rules[rule_name] = { |
| 180 | 'reg_pattern': reg_pattern, |
| 181 | 'exclude': exclude_paths, |
| 182 | 'include': include_paths, |
| 183 | 'msg': msg, |
| 184 | 'ignore_comment': ignore_comment |
| 185 | } |
| 186 | return rules |
| 187 | |
| 188 | def analyze(self, params): |
| 189 | """执行扫描任务 |