pyclean.folders   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 22
dl 0
loc 40
rs 10
c 0
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
B remove_empty_directories() 0 23 6
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