Passed
Pull Request — main (#93)
by Peter
01:11
created

pyclean.modern.normalize()   A

Complexity

Conditions 1

Size

Total Lines 8
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 1
dl 0
loc 8
rs 10
c 0
b 0
f 0
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 normalize(path_pattern: str) -> str:
94
    """
95
    Normalize path separators in a pattern for cross-platform support.
96
97
    On Windows, both forward slash and backslash are valid path separators.
98
    On Unix/Posix, only forward slash is valid (backslash can be part of filename).
99
    """
100
    return path_pattern.replace(os.sep, os.altsep or os.sep)
101
102
103
def should_ignore(path: Path, ignore_patterns: list[str]) -> bool:
104
    """
105
    Check if a path should be ignored based on ignore patterns.
106
107
    Patterns can be:
108
    - Simple names like 'bar': matches any directory with that name
109
    - Paths like 'foo/bar': matches 'bar' directory inside 'foo' directory
110
      and also ignores everything inside that directory
111
    """
112
    if not ignore_patterns:
113
        return False
114
115
    for pattern in ignore_patterns:
116
        # Check if pattern has multiple components (is a path with separators)
117
        pattern_parts = Path(normalize(pattern)).parts
118
        if len(pattern_parts) > 1:
119
            # Pattern contains path separator - match relative path
120
            # Check if the pattern matches anywhere in the path hierarchy
121
            # Path must have at least as many parts as the pattern
122
            if len(path.parts) < len(pattern_parts):
123
                continue
124
            # Check if pattern matches at any position in the path
125
            for i in range(len(path.parts) - len(pattern_parts) + 1):
126
                path_slice = path.parts[i : i + len(pattern_parts)]
127
                if path_slice == pattern_parts:
128
                    return True
129
        # Simple name - match the directory name anywhere
130
        elif path.name == pattern:
131
            return True
132
    return False
133
134
135
def remove_file(fileobj):
136
    """Attempt to delete a file object for real."""
137
    log.debug('Deleting file: %s', fileobj)
138
    try:
139
        fileobj.unlink()
140
        Runner.unlink_count += 1
141
    except OSError as err:
142
        log.debug('File not deleted. %s', err)
143
        Runner.unlink_failed += 1
144
145
146
def remove_directory(dirobj):
147
    """Attempt to remove a directory object for real."""
148
    log.debug('Removing directory: %s', dirobj)
149
    try:
150
        dirobj.rmdir()
151
        Runner.rmdir_count += 1
152
    except OSError as err:
153
        log.debug('Directory not removed. %s', err)
154
        Runner.rmdir_failed += 1
155
156
157
def print_filename(fileobj):
158
    """Only display the file name, used with --dry-run."""
159
    log.debug('Would delete file: %s', fileobj)
160
    Runner.unlink_count += 1
161
162
163
def print_dirname(dirobj):
164
    """Only display the directory name, used with --dry-run."""
165
    log.debug('Would delete directory: %s', dirobj)
166
    Runner.rmdir_count += 1
167
168
169
def pyclean(args):
170
    """Cross-platform cleaning of Python bytecode."""
171
    Runner.configure(args)
172
173
    for dir_name in args.directory:
174
        dir_path = Path(dir_name)
175
176
        log.info('Cleaning directory %s', dir_path)
177
        descend_and_clean(dir_path, BYTECODE_FILES, BYTECODE_DIRS)
178
179
        for topic in args.debris:
180
            remove_debris_for(topic, dir_path)
181
182
        remove_freeform_targets(args.erase, args.yes, dir_path)
183
184
    log.info(
185
        'Total %d files, %d directories %s.',
186
        Runner.unlink_count,
187
        Runner.rmdir_count,
188
        'would be removed' if args.dry_run else 'removed',
189
    )
190
191
    if Runner.unlink_failed or Runner.rmdir_failed:
192
        log.debug(
193
            '%d files, %d directories %s not be removed.',
194
            Runner.unlink_failed,
195
            Runner.rmdir_failed,
196
            'would' if args.dry_run else 'could',
197
        )
198
199
    # Suggest --debris option if it wasn't used
200
    if not args.debris:
201
        suggest_debris_option(args)
202
203
204
def descend_and_clean(directory, file_types, dir_names):
205
    """
206
    Walk and descend a directory tree, cleaning up files of a certain type
207
    along the way. Only delete directories if they are empty, in the end.
208
    """
209
    for child in sorted(directory.iterdir()):
210
        if child.is_file():
211
            if child.suffix in file_types:
212
                Runner.unlink(child)
213
        elif child.is_dir():
214
            if should_ignore(child, Runner.ignore):
215
                log.debug('Skipping %s', child)
216
            else:
217
                descend_and_clean(child, file_types, dir_names)
218
219
            if child.name in dir_names:
220
                Runner.rmdir(child)
221
        else:
222
            log.debug('Ignoring %s (neither a file nor a folder)', child)
223
224
225
def remove_debris_for(topic, directory):
226
    """
227
    Clean up debris for a specific topic.
228
    """
229
    log.debug('Scanning for debris of %s ...', topic.title())
230
231
    for path_glob in DEBRIS_TOPICS[topic]:
232
        delete_filesystem_objects(directory, path_glob, recursive=True)
233
234
235
def remove_freeform_targets(glob_patterns, yes, directory):
236
    """
237
    Remove free-form targets using globbing.
238
239
    This is **potentially dangerous** since users can delete everything
240
    anywhere in their file system, including the entire project they're
241
    working on. For this reason, the implementation imposes the following
242
    (user experience-related) restrictions:
243
244
    - Deleting (directories) is not recursive, directory contents must be
245
      explicitly specified using globbing (e.g. ``dirname/**/*``).
246
    - The user is responsible for the deletion order, so that a directory
247
      is empty when it is attempted to be deleted.
248
    - A confirmation prompt for the deletion of every single file system
249
      object is shown (unless the ``--yes`` option is used, in addition).
250
    """
251
    for path_glob in glob_patterns:
252
        log.debug('Erase file system objects matching: %s', path_glob)
253
        delete_filesystem_objects(directory, path_glob, prompt=not yes)
254
255
256
def delete_filesystem_objects(directory, path_glob, prompt=False, recursive=False):
257
    """
258
    Identifies all pathnames matching a specific glob pattern, and attempts
259
    to delete them in the proper order, optionally asking for confirmation.
260
261
    Implementation Note: We sort the file system objects in *reverse order*
262
    and first delete *all files* before removing directories. This way we
263
    make sure that the directories that are deepest down in the hierarchy
264
    are empty (for both files & directories) when we attempt to remove them.
265
    """
266
    all_names = sorted(directory.glob(path_glob), reverse=True)
267
    dirs = (name for name in all_names if name.is_dir() and not name.is_symlink())
268
    files = (name for name in all_names if not name.is_dir() or name.is_symlink())
269
270
    for file_object in files:
271
        file_type = 'symlink' if file_object.is_symlink() else 'file'
272
        if prompt and not confirm('Delete %s %s' % (file_type, file_object)):
273
            Runner.unlink_failed += 1
274
            continue
275
        Runner.unlink(file_object)
276
277
    for dir_object in dirs:
278
        if prompt and not confirm('Remove empty directory %s' % dir_object):
279
            Runner.rmdir_failed += 1
280
            continue
281
        Runner.rmdir(dir_object)
282
283
    if recursive:
284
        subdirs = (Path(name.path) for name in os.scandir(directory) if name.is_dir())
285
        for subdir in subdirs:
286
            if should_ignore(subdir, Runner.ignore):
287
                log.debug('Skipping %s', subdir)
288
            else:
289
                delete_filesystem_objects(subdir, path_glob, prompt, recursive)
290
291
292
def confirm(message):
293
    """An interactive confirmation prompt."""
294
    try:
295
        answer = input('%s? ' % message)
296
        return answer.strip().lower() in ['y', 'yes']
297
    except KeyboardInterrupt:
298
        msg = 'Aborted by user.'
299
        raise SystemExit(msg)
300
301
302
def detect_debris_in_directory(directory):
303
    """
304
    Scan a directory for debris artifacts and return a list of detected topics.
305
    """
306
    detected_topics = []
307
308
    for topic, patterns in DEBRIS_TOPICS.items():
309
        for pattern in patterns:
310
            # Skip patterns that are for recursive cleanup (contain **)
311
            if '**' in pattern:
312
                continue
313
            # Check if the pattern matches anything in the directory
314
            matches = list(directory.glob(pattern))
315
            if matches:
316
                detected_topics.append(topic)
317
                break  # Found at least one match for this topic, move to next
318
319
    return detected_topics
320
321
322
def suggest_debris_option(args):
323
    """
324
    Suggest using the --debris option when it wasn't used.
325
    Optionally provide targeted suggestions based on detected artifacts.
326
    """
327
    # Collect all detected debris topics across all directories
328
    all_detected = set()
329
    for dir_name in args.directory:
330
        dir_path = Path(dir_name)
331
        if dir_path.exists():
332
            detected = detect_debris_in_directory(dir_path)
333
            all_detected.update(detected)
334
335
    if all_detected:
336
        # Provide targeted suggestion
337
        topics_str = ' '.join(sorted(all_detected))
338
        log.info(
339
            'Hint: Use --debris to also clean up build artifacts. Detected: %s',
340
            topics_str,
341
        )
342
    else:
343
        # Provide general suggestion
344
        log.info(
345
            'Hint: Use --debris to also clean up build artifacts '
346
            'from common Python development tools.',
347
        )
348