Load self from a .RULE file with YAMl frontmatter stored in rule_file. Unknown fields are ignored and not bound to the Rule object. Optionally check for consistency if ``with_checks`` is True.
(self, rule_file, with_checks=True)
| 2423 | of.write(output) |
| 2424 | |
| 2425 | def load(self, rule_file, with_checks=True): |
| 2426 | """ |
| 2427 | Load self from a .RULE file with YAMl frontmatter stored in rule_file. |
| 2428 | Unknown fields are ignored and not bound to the Rule object. |
| 2429 | Optionally check for consistency if ``with_checks`` is True. |
| 2430 | """ |
| 2431 | try: |
| 2432 | content, data = load_frontmatter(rule_file) |
| 2433 | if not content: |
| 2434 | raise InvalidRule( |
| 2435 | f'Cannot load rule with empty text: ' |
| 2436 | f'{self}: file://{rule_file}' |
| 2437 | ) |
| 2438 | |
| 2439 | self.text = content.lstrip() |
| 2440 | |
| 2441 | except Exception as e: |
| 2442 | print('#############################') |
| 2443 | print('INVALID LICENSE RULE FILE:', f'file://{rule_file}') |
| 2444 | print('#############################') |
| 2445 | print(e) |
| 2446 | print('#############################') |
| 2447 | # this is a rare case, but yes we abruptly stop. |
| 2448 | raise e |
| 2449 | |
| 2450 | known_attributes = set(attr.fields_dict(self.__class__)) |
| 2451 | data_file_attributes = set(data) |
| 2452 | if with_checks: |
| 2453 | unknown_attributes = data_file_attributes.difference(known_attributes) |
| 2454 | if unknown_attributes: |
| 2455 | unknown_attributes = ', '.join(sorted(unknown_attributes)) |
| 2456 | msg = 'License rule {} data file has unknown attributes: {}' |
| 2457 | raise InvalidRule(msg.format(self, unknown_attributes)) |
| 2458 | |
| 2459 | self.license_expression = data.get('license_expression') |
| 2460 | |
| 2461 | self.is_false_positive = data.get('is_false_positive', False) |
| 2462 | |
| 2463 | self.is_required_phrase = data.get('is_required_phrase', False) |
| 2464 | self.skip_for_required_phrase_generation = data.get('skip_for_required_phrase_generation', False) |
| 2465 | self.source = data.get('source') |
| 2466 | |
| 2467 | stored_relevance = data.get('relevance', None) |
| 2468 | |
| 2469 | # Keep track if we have a stored relevance of not. |
| 2470 | if stored_relevance is None: |
| 2471 | self.relevance = 100 |
| 2472 | self.has_stored_relevance = False |
| 2473 | else: |
| 2474 | self.has_stored_relevance = True |
| 2475 | self.relevance = as_int(float(stored_relevance)) |
| 2476 | |
| 2477 | minimum_coverage = as_int(float(data.get('minimum_coverage') or 0)) |
| 2478 | self._minimum_containment = minimum_coverage / 100 |
| 2479 | if minimum_coverage: |
| 2480 | # Keep track if we have a stored minimum_coverage of not. |
| 2481 | self.minimum_coverage = minimum_coverage |
| 2482 | self.has_stored_minimum_coverage = True |