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

pyclean.modern   F

Complexity

Total Complexity 61

Size/Duplication

Total Lines 350
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 201
dl 0
loc 350
rs 3.52
c 0
b 0
f 0
wmc 61

2 Methods

Rating   Name   Duplication   Size   Complexity  
A CleanupRunner.configure() 0 9 3
A CleanupRunner.__init__() 0 9 1

13 Functions

Rating   Name   Duplication   Size   Complexity  
A remove_directory() 0 9 2
A confirm() 0 8 2
C delete_filesystem_objects() 0 34 11
A detect_debris_in_directory() 0 18 5
A print_filename() 0 4 1
A remove_file() 0 9 2
B descend_and_clean() 0 19 7
A print_dirname() 0 4 1
A remove_freeform_targets() 0 19 2
A remove_debris_for() 0 8 2
B pyclean() 0 33 8
A suggest_debris_option() 0 24 4
C should_ignore() 0 44 10

How to fix   Complexity   

Complexity

Complex classes like pyclean.modern 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
"""
6
Modern, cross-platform, pure-Python pyclean implementation.
7
"""
8
9
import logging
10
import os
11
from pathlib import Path
12
13
BYTECODE_FILES = ['.pyc', '.pyo']
14
BYTECODE_DIRS = ['__pycache__']
15
DEBRIS_TOPICS = {
16
    'cache': [
17
        '.cache/**/*',
18
        '.cache/',
19
    ],
20
    'coverage': [
21
        '.coverage',
22
        'coverage.json',
23
        'coverage.lcov',
24
        'coverage.xml',
25
        'htmlcov/**/*',
26
        'htmlcov/',
27
    ],
28
    'jupyter': [
29
        '.ipynb_checkpoints/**/*',
30
        '.ipynb_checkpoints/',
31
    ],
32
    'mypy': [
33
        '.mypy_cache/**/*',
34
        '.mypy_cache/',
35
    ],
36
    'package': [
37
        'build/bdist.*/**/*',
38
        'build/bdist.*/',
39
        'build/lib/**/*',
40
        'build/lib/',
41
        'build/',
42
        'dist/**/*',
43
        'dist/',
44
        'sdist/**/*',
45
        'sdist/',
46
        '*.egg-info/**/*',
47
        '*.egg-info/',
48
    ],
49
    'pytest': [
50
        '.pytest_cache/**/*',
51
        '.pytest_cache/',
52
        'pytestdebug.log',
53
    ],
54
    'ruff': [
55
        '.ruff_cache/**/*',
56
        '.ruff_cache/',
57
    ],
58
    'tox': [
59
        '.tox/**/*',
60
        '.tox/',
61
    ],
62
}
63
64
65
class CleanupRunner:
66
    """Module-level configuration and value store."""
67
68
    def __init__(self):
69
        """Cleanup runner with optional dry-run behavior."""
70
        self.unlink = None
71
        self.rmdir = None
72
        self.ignore = None
73
        self.unlink_count = None
74
        self.unlink_failed = None
75
        self.rmdir_count = None
76
        self.rmdir_failed = None
77
78
    def configure(self, args):
79
        """Set up runner according to command line options."""
80
        self.unlink = print_filename if args.dry_run else remove_file
81
        self.rmdir = print_dirname if args.dry_run else remove_directory
82
        self.ignore = args.ignore
83
        self.unlink_count = 0
84
        self.unlink_failed = 0
85
        self.rmdir_count = 0
86
        self.rmdir_failed = 0
87
88
89
log = logging.getLogger(__name__)
90
Runner = CleanupRunner()
91
92
93
def should_ignore(path, ignore_patterns):
94
    """
95
    Check if a path should be ignored based on ignore patterns.
96
97
    Patterns can be:
98
    - Simple names like 'bar': matches any directory with that name
99
    - Paths like 'foo/bar': matches 'bar' directory inside 'foo' directory
100
      and also ignores everything inside that directory
101
102
    Args:
103
        path: Path object to check
104
        ignore_patterns: List of ignore patterns
105
106
    Returns:
107
        True if the path should be ignored, False otherwise
108
    """
109
    if not ignore_patterns:
110
        return False
111
112
    for pattern in ignore_patterns:
113
        # Check for path separator (support both Unix '/' and Windows '\')
114
        # Normalize backslashes to forward slashes for consistent handling
115
        if '/' in pattern or '\\' in pattern:
116
            # Pattern contains path separator - match relative path
117
            # Check if the pattern matches anywhere in the path hierarchy
118
            try:
119
                # Normalize the pattern to use forward slashes
120
                normalized_pattern = pattern.replace('\\', '/')
121
                # Get parts from the pattern
122
                pattern_parts = Path(normalized_pattern).parts
123
                # Path must have at least as many parts as the pattern
124
                if len(path.parts) < len(pattern_parts):
125
                    continue
126
                # Check if pattern matches at any position in the path
127
                for i in range(len(path.parts) - len(pattern_parts) + 1):
128
                    path_slice = path.parts[i : i + len(pattern_parts)]
129
                    if path_slice == pattern_parts:
130
                        return True
131
            except (ValueError, IndexError):
132
                continue
133
        # Simple name - match the directory name anywhere
134
        elif path.name == pattern:
135
            return True
136
    return False
137
138
139
def remove_file(fileobj):
140
    """Attempt to delete a file object for real."""
141
    log.debug('Deleting file: %s', fileobj)
142
    try:
143
        fileobj.unlink()
144
        Runner.unlink_count += 1
145
    except OSError as err:
146
        log.debug('File not deleted. %s', err)
147
        Runner.unlink_failed += 1
148
149
150
def remove_directory(dirobj):
151
    """Attempt to remove a directory object for real."""
152
    log.debug('Removing directory: %s', dirobj)
153
    try:
154
        dirobj.rmdir()
155
        Runner.rmdir_count += 1
156
    except OSError as err:
157
        log.debug('Directory not removed. %s', err)
158
        Runner.rmdir_failed += 1
159
160
161
def print_filename(fileobj):
162
    """Only display the file name, used with --dry-run."""
163
    log.debug('Would delete file: %s', fileobj)
164
    Runner.unlink_count += 1
165
166
167
def print_dirname(dirobj):
168
    """Only display the directory name, used with --dry-run."""
169
    log.debug('Would delete directory: %s', dirobj)
170
    Runner.rmdir_count += 1
171
172
173
def pyclean(args):
174
    """Cross-platform cleaning of Python bytecode."""
175
    Runner.configure(args)
176
177
    for dir_name in args.directory:
178
        dir_path = Path(dir_name)
179
180
        log.info('Cleaning directory %s', dir_path)
181
        descend_and_clean(dir_path, BYTECODE_FILES, BYTECODE_DIRS)
182
183
        for topic in args.debris:
184
            remove_debris_for(topic, dir_path)
185
186
        remove_freeform_targets(args.erase, args.yes, dir_path)
187
188
    log.info(
189
        'Total %d files, %d directories %s.',
190
        Runner.unlink_count,
191
        Runner.rmdir_count,
192
        'would be removed' if args.dry_run else 'removed',
193
    )
194
195
    if Runner.unlink_failed or Runner.rmdir_failed:
196
        log.debug(
197
            '%d files, %d directories %s not be removed.',
198
            Runner.unlink_failed,
199
            Runner.rmdir_failed,
200
            'would' if args.dry_run else 'could',
201
        )
202
203
    # Suggest --debris option if it wasn't used
204
    if not args.debris:
205
        suggest_debris_option(args)
206
207
208
def descend_and_clean(directory, file_types, dir_names):
209
    """
210
    Walk and descend a directory tree, cleaning up files of a certain type
211
    along the way. Only delete directories if they are empty, in the end.
212
    """
213
    for child in sorted(directory.iterdir()):
214
        if child.is_file():
215
            if child.suffix in file_types:
216
                Runner.unlink(child)
217
        elif child.is_dir():
218
            if should_ignore(child, Runner.ignore):
219
                log.debug('Skipping %s', child)
220
            else:
221
                descend_and_clean(child, file_types, dir_names)
222
223
            if child.name in dir_names:
224
                Runner.rmdir(child)
225
        else:
226
            log.debug('Ignoring %s (neither a file nor a folder)', child)
227
228
229
def remove_debris_for(topic, directory):
230
    """
231
    Clean up debris for a specific topic.
232
    """
233
    log.debug('Scanning for debris of %s ...', topic.title())
234
235
    for path_glob in DEBRIS_TOPICS[topic]:
236
        delete_filesystem_objects(directory, path_glob, recursive=True)
237
238
239
def remove_freeform_targets(glob_patterns, yes, directory):
240
    """
241
    Remove free-form targets using globbing.
242
243
    This is **potentially dangerous** since users can delete everything
244
    anywhere in their file system, including the entire project they're
245
    working on. For this reason, the implementation imposes the following
246
    (user experience-related) restrictions:
247
248
    - Deleting (directories) is not recursive, directory contents must be
249
      explicitly specified using globbing (e.g. ``dirname/**/*``).
250
    - The user is responsible for the deletion order, so that a directory
251
      is empty when it is attempted to be deleted.
252
    - A confirmation prompt for the deletion of every single file system
253
      object is shown (unless the ``--yes`` option is used, in addition).
254
    """
255
    for path_glob in glob_patterns:
256
        log.debug('Erase file system objects matching: %s', path_glob)
257
        delete_filesystem_objects(directory, path_glob, prompt=not yes)
258
259
260
def delete_filesystem_objects(directory, path_glob, prompt=False, recursive=False):
261
    """
262
    Identifies all pathnames matching a specific glob pattern, and attempts
263
    to delete them in the proper order, optionally asking for confirmation.
264
265
    Implementation Note: We sort the file system objects in *reverse order*
266
    and first delete *all files* before removing directories. This way we
267
    make sure that the directories that are deepest down in the hierarchy
268
    are empty (for both files & directories) when we attempt to remove them.
269
    """
270
    all_names = sorted(directory.glob(path_glob), reverse=True)
271
    dirs = (name for name in all_names if name.is_dir() and not name.is_symlink())
272
    files = (name for name in all_names if not name.is_dir() or name.is_symlink())
273
274
    for file_object in files:
275
        file_type = 'symlink' if file_object.is_symlink() else 'file'
276
        if prompt and not confirm('Delete %s %s' % (file_type, file_object)):
277
            Runner.unlink_failed += 1
278
            continue
279
        Runner.unlink(file_object)
280
281
    for dir_object in dirs:
282
        if prompt and not confirm('Remove empty directory %s' % dir_object):
283
            Runner.rmdir_failed += 1
284
            continue
285
        Runner.rmdir(dir_object)
286
287
    if recursive:
288
        subdirs = (Path(name.path) for name in os.scandir(directory) if name.is_dir())
289
        for subdir in subdirs:
290
            if should_ignore(subdir, Runner.ignore):
291
                log.debug('Skipping %s', subdir)
292
            else:
293
                delete_filesystem_objects(subdir, path_glob, prompt, recursive)
294
295
296
def confirm(message):
297
    """An interactive confirmation prompt."""
298
    try:
299
        answer = input('%s? ' % message)
300
        return answer.strip().lower() in ['y', 'yes']
301
    except KeyboardInterrupt:
302
        msg = 'Aborted by user.'
303
        raise SystemExit(msg)
304
305
306
def detect_debris_in_directory(directory):
307
    """
308
    Scan a directory for debris artifacts and return a list of detected topics.
309
    """
310
    detected_topics = []
311
312
    for topic, patterns in DEBRIS_TOPICS.items():
313
        for pattern in patterns:
314
            # Skip patterns that are for recursive cleanup (contain **)
315
            if '**' in pattern:
316
                continue
317
            # Check if the pattern matches anything in the directory
318
            matches = list(directory.glob(pattern))
319
            if matches:
320
                detected_topics.append(topic)
321
                break  # Found at least one match for this topic, move to next
322
323
    return detected_topics
324
325
326
def suggest_debris_option(args):
327
    """
328
    Suggest using the --debris option when it wasn't used.
329
    Optionally provide targeted suggestions based on detected artifacts.
330
    """
331
    # Collect all detected debris topics across all directories
332
    all_detected = set()
333
    for dir_name in args.directory:
334
        dir_path = Path(dir_name)
335
        if dir_path.exists():
336
            detected = detect_debris_in_directory(dir_path)
337
            all_detected.update(detected)
338
339
    if all_detected:
340
        # Provide targeted suggestion
341
        topics_str = ' '.join(sorted(all_detected))
342
        log.info(
343
            'Hint: Use --debris to also clean up build artifacts. Detected: %s',
344
            topics_str,
345
        )
346
    else:
347
        # Provide general suggestion
348
        log.info(
349
            'Hint: Use --debris to also clean up build artifacts '
350
            'from common Python development tools.',
351
        )
352