pyclean.folders.remove_empty_directories()   B
last analyzed

Complexity

Conditions 6

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 23
rs 8.6666
c 0
b 0
f 0
cc 6
nop 1
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 = [entry for entry in os.scandir(directory) if entry.is_dir()]
26
    except (OSError, PermissionError) as err:
27
        log.warning('Cannot access directory %s: %s', directory, err)
28
        return
29
30
    for subdir in subdirs:
31
        if should_ignore(subdir.path, Runner.ignore):
32
            log.debug('Skipping %s', subdir.name)
33
        else:
34
            remove_empty_directories(subdir.path)
35
            try:
36
                if not any(os.scandir(subdir.path)):
37
                    Runner.rmdir(Path(subdir.path))
38
            except (OSError, PermissionError) as err:
39
                log.debug('Cannot check or remove directory %s: %s', subdir.path, err)
40