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

pyclean.usability.delete_filesystem_objects()   C

Complexity

Conditions 10

Size

Total Lines 25
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 25
rs 5.9999
c 0
b 0
f 0
cc 10
nop 4

How to fix   Complexity   

Complexity

Complex classes like pyclean.usability.delete_filesystem_objects() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
# SPDX-FileCopyrightText: 2020 Peter Bittner <[email protected]>
2
#
3
# SPDX-License-Identifier: GPL-3.0-or-later
4
5
import logging
6
7
from .runner import Runner
8
9
log = logging.getLogger(__name__)
10
11
12
def confirm(message):
13
    try:
14
        answer = input('%s? ' % message)
15
        return answer.strip().lower() in ['y', 'yes']
16
    except KeyboardInterrupt:
17
        msg = 'Aborted by user.'
18
        raise SystemExit(msg)
19
20
21
def delete_filesystem_objects(directory, path_glob, prompt=False, dry_run=False):
22
    all_names = sorted(directory.glob(path_glob), reverse=True)
23
    dirs = (name for name in all_names if name.is_dir() and not name.is_symlink())
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable name does not seem to be defined.
Loading history...
24
    files = (name for name in all_names if not name.is_dir() or name.is_symlink())
25
26
    for file_object in files:
27
        file_type = 'symlink' if file_object.is_symlink() else 'file'
28
        if (
29
            not dry_run
30
            and prompt
31
            and not confirm('Delete %s %s' % (file_type, file_object))
32
        ):
33
            Runner.unlink_failed += 1
34
            continue
35
        Runner.unlink(file_object)
36
37
    for dir_object in dirs:
38
        if (
39
            not dry_run
40
            and prompt
41
            and not confirm('Remove empty directory %s' % dir_object)
42
        ):
43
            Runner.rmdir_failed += 1
44
            continue
45
        Runner.rmdir(dir_object)
46
47
48
def remove_freeform_targets(directory, glob_patterns, yes, dry_run=False):
49
    for path_glob in glob_patterns:
50
        log.debug('Erase file system objects matching: %s', path_glob)
51
        delete_filesystem_objects(directory, path_glob, prompt=not yes, dry_run=dry_run)
52