Passed
Pull Request — main (#107)
by
unknown
01:09
created

pyclean.folders.remove_empty_directories()   B

Complexity

Conditions 6

Size

Total Lines 19
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 19
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
import logging
6
import os
7
from pathlib import Path
8
9
from .runner import Runner
10
from .traversal import should_ignore
11
12
log = logging.getLogger(__name__)
13
14
15
def remove_empty_directories(directory):
16
    try:
17
        subdirs = [
18
            Path(entry.path) for entry in os.scandir(directory) if entry.is_dir()
19
        ]
20
    except (OSError, PermissionError) as err:
21
        log.warning('Cannot access directory %s: %s', directory, err)
22
        return
23
24
    for subdir in subdirs:
25
        if should_ignore(subdir, Runner.ignore):
26
            log.debug('Skipping %s', subdir)
27
        else:
28
            remove_empty_directories(subdir)
29
            try:
30
                if next(subdir.iterdir(), None) is None:
31
                    Runner.rmdir(subdir)
32
            except (OSError, PermissionError) as err:
33
                log.debug('Cannot check or remove directory %s: %s', subdir, err)
34