| Total Complexity | 6 |
| Total Lines | 42 |
| 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 | """Empty directory removal.""" |
||
| 6 | |||
| 7 | import logging |
||
| 8 | import os |
||
| 9 | from pathlib import Path |
||
| 10 | |||
| 11 | from .runner import Runner |
||
| 12 | from .traversal import should_ignore |
||
| 13 | |||
| 14 | log = logging.getLogger(__name__) |
||
| 15 | |||
| 16 | |||
| 17 | def remove_empty_directories(directory): |
||
| 18 | """ |
||
| 19 | Recursively remove empty directories in the given directory tree. |
||
| 20 | |||
| 21 | This walks the directory tree in post-order (bottom-up), attempting to |
||
| 22 | remove directories that are empty. |
||
| 23 | """ |
||
| 24 | try: |
||
| 25 | subdirs = [ |
||
| 26 | Path(entry.path) for entry in os.scandir(directory) if entry.is_dir() |
||
| 27 | ] |
||
| 28 | except (OSError, PermissionError) as err: |
||
| 29 | log.warning('Cannot access directory %s: %s', directory, err) |
||
| 30 | return |
||
| 31 | |||
| 32 | for subdir in subdirs: |
||
| 33 | if should_ignore(subdir, Runner.ignore): |
||
| 34 | log.debug('Skipping %s', subdir) |
||
| 35 | else: |
||
| 36 | remove_empty_directories(subdir) |
||
| 37 | try: |
||
| 38 | if next(subdir.iterdir(), None) is None: |
||
| 39 | Runner.rmdir(subdir) |
||
| 40 | except (OSError, PermissionError) as err: |
||
| 41 | log.debug('Cannot check or remove directory %s: %s', subdir, err) |
||
| 42 |