| Total Complexity | 16 |
| Total Lines | 51 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | # SPDX-FileCopyrightText: 2020 Peter Bittner <[email protected]> |
||
| 2 | # |
||
| 3 | # SPDX-License-Identifier: GPL-3.0-or-later |
||
| 4 | |||
| 5 | import logging |
||
| 6 | import os |
||
| 7 | from pathlib import Path |
||
| 8 | |||
| 9 | from .runner import Runner |
||
| 10 | |||
| 11 | log = logging.getLogger(__name__) |
||
| 12 | |||
| 13 | |||
| 14 | def normalize(path_pattern: str) -> str: |
||
| 15 | return path_pattern.replace(os.sep, os.altsep or os.sep) |
||
| 16 | |||
| 17 | |||
| 18 | def should_ignore(path: Path, ignore_patterns: list[str]) -> bool: |
||
| 19 | if not ignore_patterns: |
||
| 20 | return False |
||
| 21 | |||
| 22 | for pattern in ignore_patterns: |
||
| 23 | pattern_parts = Path(normalize(pattern)).parts |
||
| 24 | if len(pattern_parts) > 1: |
||
| 25 | if len(path.parts) < len(pattern_parts): |
||
| 26 | continue |
||
| 27 | for i in range(len(path.parts) - len(pattern_parts) + 1): |
||
| 28 | path_slice = path.parts[i : i + len(pattern_parts)] |
||
| 29 | if path_slice == pattern_parts: |
||
| 30 | return True |
||
| 31 | elif path.name == pattern: |
||
| 32 | return True |
||
| 33 | return False |
||
| 34 | |||
| 35 | |||
| 36 | def descend_and_clean(directory, file_types, dir_names): |
||
| 37 | for child in sorted(directory.iterdir()): |
||
| 38 | if child.is_file(): |
||
| 39 | if child.suffix in file_types: |
||
| 40 | Runner.unlink(child) |
||
| 41 | elif child.is_dir(): |
||
| 42 | if should_ignore(child, Runner.ignore): |
||
| 43 | log.debug('Skipping %s', child) |
||
| 44 | else: |
||
| 45 | descend_and_clean(child, file_types, dir_names) |
||
| 46 | |||
| 47 | if child.name in dir_names: |
||
| 48 | Runner.rmdir(child) |
||
| 49 | else: |
||
| 50 | log.debug('Ignoring %s (neither a file nor a folder)', child) |
||
| 51 |