|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +"""Applies a blocklist to requirements files.""" |
| 4 | + |
| 5 | +import fileinput |
| 6 | +from pathlib import Path |
| 7 | +import re |
| 8 | +import sys |
| 9 | + |
| 10 | +from packaging.requirements import Requirement |
| 11 | + |
| 12 | +PROJECT_ROOT = Path(__file__).parent.parent.absolute() |
| 13 | +BLOCKLIST_PATH = PROJECT_ROOT / "requirements/blocklist.in" |
| 14 | + |
| 15 | + |
| 16 | +def is_requirement(line): |
| 17 | + """Returns True if the line is an actual requirement.""" |
| 18 | + |
| 19 | + def empty(): |
| 20 | + return not line.strip() |
| 21 | + |
| 22 | + def comment(): |
| 23 | + return re.match(r"^\s*#", line) |
| 24 | + |
| 25 | + return not empty() and not comment() |
| 26 | + |
| 27 | + |
| 28 | +def parse_blocklist(): |
| 29 | + """Parses a list of blocked requirements.""" |
| 30 | + with open(BLOCKLIST_PATH, encoding="utf-8") as file: |
| 31 | + for line in file: |
| 32 | + if is_requirement(line): |
| 33 | + yield line.strip() |
| 34 | + |
| 35 | + |
| 36 | +def parse_requirements(): |
| 37 | + """Parses the requirement file(s) given as an input.""" |
| 38 | + for line in fileinput.input(encoding="utf-8"): |
| 39 | + if is_requirement(line): |
| 40 | + yield Requirement(line) |
| 41 | + |
| 42 | + |
| 43 | +def filtered_requirements_lines(): |
| 44 | + """Parses the requirement file(s) given as an input. |
| 45 | + Filters out all sections that represent a blocked requirement. |
| 46 | + """ |
| 47 | + include_section = True |
| 48 | + blocked_requirements = set(parse_blocklist()) |
| 49 | + |
| 50 | + for line in fileinput.input(encoding="utf-8"): |
| 51 | + if is_requirement(line): |
| 52 | + name = Requirement(line).name |
| 53 | + include_section = name not in blocked_requirements |
| 54 | + if not include_section: |
| 55 | + print(f"Removing blocked requirement: {name}", file=sys.stderr) |
| 56 | + if include_section: |
| 57 | + yield line |
| 58 | + |
| 59 | + |
| 60 | +def main(): |
| 61 | + """Applies the blocklist to the requirements file(s) given as |
| 62 | + an input. Removes blocked requirements. |
| 63 | + """ |
| 64 | + for line in filtered_requirements_lines(): |
| 65 | + print(line, end="") |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + try: |
| 70 | + main() |
| 71 | + except BrokenPipeError: |
| 72 | + # play nice with Unix pipelines |
| 73 | + pass |
0 commit comments