|
| 1 | +from typing import Optional |
| 2 | + |
| 3 | +from sourcery_rules_generator import yaml_converter |
| 4 | +from sourcery_rules_generator.models import SourceryCustomRule, PathsConfig |
| 5 | + |
| 6 | + |
| 7 | +def create_yaml_rules(name_to_avoid: str): |
| 8 | + |
| 9 | + custom_rules = create_sourcery_custom_rules(name_to_avoid) |
| 10 | + |
| 11 | + rules_dict = {"rules": [rule.dict(exclude_unset=True) for rule in custom_rules]} |
| 12 | + return yaml_converter.dumps(rules_dict) |
| 13 | + |
| 14 | + |
| 15 | +def create_sourcery_custom_rules(name_to_avoid: str) -> str: |
| 16 | + description = f"Don't use the name {name_to_avoid}" |
| 17 | + |
| 18 | + function_name_rule = SourceryCustomRule( |
| 19 | + id=f"no-{name_to_avoid}-function-name", |
| 20 | + description=description, |
| 21 | + tags=["naming", f"no-{name_to_avoid}"], |
| 22 | + pattern=""" |
| 23 | +def ${function_name}(...): |
| 24 | + ... |
| 25 | +""", |
| 26 | + condition=f'function_name.contains("{name_to_avoid}")', |
| 27 | + ) |
| 28 | + |
| 29 | + function_arg_rule = SourceryCustomRule( |
| 30 | + id=f"no-{name_to_avoid}-function-arg", |
| 31 | + description=description, |
| 32 | + tags=["naming", f"no-{name_to_avoid}"], |
| 33 | + pattern=""" |
| 34 | +def ...(...,${arg_name}: ${type?} = ${default_value?},...): |
| 35 | + ... |
| 36 | +""", |
| 37 | + condition=f'arg_name.contains("{name_to_avoid}")', |
| 38 | + ) |
| 39 | + |
| 40 | + class_name_rule = SourceryCustomRule( |
| 41 | + id=f"no-{name_to_avoid}-class-name", |
| 42 | + description=description, |
| 43 | + tags=["naming", f"no-{name_to_avoid}"], |
| 44 | + pattern=""" |
| 45 | +class ${class_name}(...): |
| 46 | + ... |
| 47 | +""", |
| 48 | + condition=f'class_name.contains("{name_to_avoid}")', |
| 49 | + ) |
| 50 | + |
| 51 | + variable_declaration_rule = SourceryCustomRule( |
| 52 | + id=f"no-{name_to_avoid}-property", |
| 53 | + description=description, |
| 54 | + tags=["naming", f"no-{name_to_avoid}"], |
| 55 | + pattern="${var}: ${type}", |
| 56 | + condition=f'var.contains("{name_to_avoid}")', |
| 57 | + ) |
| 58 | + |
| 59 | + variable_assignment_rule = SourceryCustomRule( |
| 60 | + id=f"no-{name_to_avoid}-variable", |
| 61 | + description=description, |
| 62 | + tags=["naming", f"no-{name_to_avoid}"], |
| 63 | + pattern="${var} = ${value}", |
| 64 | + condition=f'var.contains("{name_to_avoid}")', |
| 65 | + ) |
| 66 | + |
| 67 | + return ( |
| 68 | + function_name_rule, |
| 69 | + function_arg_rule, |
| 70 | + class_name_rule, |
| 71 | + variable_declaration_rule, |
| 72 | + variable_assignment_rule, |
| 73 | + ) |
0 commit comments