Passed
Push — main ( c1ae8e...0e16f8 )
by Peter
01:21
created

pyclean.cli   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 167
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 113
dl 0
loc 167
rs 10
c 0
b 0
f 0
wmc 15

3 Functions

Rating   Name   Duplication   Size   Complexity  
D parse_arguments() 0 123 9
A main() 0 13 3
A init_logging() 0 9 3
1
# SPDX-FileCopyrightText: 2019 Peter Bittner <[email protected]>
2
#
3
# SPDX-License-Identifier: GPL-3.0-or-later
4
5
"""
6
Command line interface implementation for pyclean.
7
"""
8
9
import argparse
10
import logging
11
import shutil
12
13
from . import __version__, modern
14
15
log = logging.getLogger(__name__)
16
17
18
def parse_arguments():
19
    """
20
    Parse and handle CLI arguments.
21
    """
22
    debris_default_topics = ['cache', 'coverage', 'package', 'pytest', 'ruff']
23
    debris_optional_topics = ['jupyter', 'mypy', 'tox']
24
    debris_choices = ['all', *debris_default_topics, *debris_optional_topics]
25
    ignore_default_items = [
26
        '.git',
27
        '.hg',
28
        '.svn',
29
        '.tox',
30
        '.venv',
31
        'node_modules',
32
        'venv',
33
    ]
34
35
    parser = argparse.ArgumentParser(
36
        description=(
37
            'Remove bytecode files, cache directories, build and test artifacts '
38
            'and other debris in your Python project or elsewhere.'
39
        ),
40
        epilog='Made with ♥ by Painless Software, 🄯 Peter Bittner.',
41
    )
42
43
    parser.add_argument('--version', action='version', version=__version__)
44
    parser.add_argument(
45
        'directory',
46
        nargs='+',
47
        help='directory tree to traverse for bytecode and debris',
48
    )
49
    parser.add_argument(
50
        '-d',
51
        '--debris',
52
        metavar='TOPIC',
53
        action='extend',
54
        nargs='*',
55
        default=argparse.SUPPRESS,
56
        choices=debris_choices,
57
        help='remove leftovers from popular Python development tools'
58
        ' (may be specified multiple times; optional: all %s; default: %s)'
59
        % (
60
            ' '.join(debris_optional_topics),
61
            ' '.join(debris_default_topics),
62
        ),
63
    )
64
    parser.add_argument(
65
        '-e',
66
        '--erase',
67
        metavar='PATTERN',
68
        action='extend',
69
        nargs='+',
70
        default=[],
71
        help='delete files or folders matching a globbing pattern (may be specified'
72
        ' multiple times); this will be interactive unless --yes is used.',
73
    )
74
    parser.add_argument(
75
        '-f',
76
        '--folders',
77
        action='store_true',
78
        help='remove empty directories',
79
    )
80
    parser.add_argument(
81
        '-g',
82
        '--git-clean',
83
        action='store_true',
84
        default=False,
85
        help='run git clean to remove untracked files',
86
    )
87
    parser.add_argument(
88
        '-i',
89
        '--ignore',
90
        metavar='DIRECTORY',
91
        action='extend',
92
        nargs='+',
93
        default=ignore_default_items,
94
        help='directory that should be ignored (may be specified multiple times;'
95
        ' default: %s)' % ' '.join(ignore_default_items),
96
    )
97
    parser.add_argument(
98
        '-n',
99
        '--dry-run',
100
        action='store_true',
101
        help='show what would be done',
102
    )
103
104
    verbosity = parser.add_mutually_exclusive_group()
105
    verbosity.add_argument('-q', '--quiet', action='store_true', help='be quiet')
106
    verbosity.add_argument(
107
        '-v',
108
        '--verbose',
109
        action='store_true',
110
        help='be more verbose',
111
    )
112
113
    parser.add_argument(
114
        '-y',
115
        '--yes',
116
        action='store_true',
117
        help='assume yes as answer for interactive questions',
118
    )
119
120
    args = parser.parse_args()
121
    init_logging(args)
122
123
    if args.git_clean and not shutil.which('git') is not None:
124
        parser.error('Git is not available. Install Git to use --git-clean.')
125
126
    if args.yes and not args.erase and not args.git_clean:
127
        parser.error('Specifying --yes only makes sense with --erase or --git-clean.')
128
129
    if 'debris' in args:
130
        if 'all' in args.debris:
131
            args.debris = debris_default_topics + debris_optional_topics
132
        elif not args.debris:
133
            args.debris = debris_default_topics
134
        log.debug('Debris topics to scan for: %s', ' '.join(args.debris))
135
    else:
136
        args.debris = []
137
138
    log.debug('Ignored directories: %s', ' '.join(args.ignore))
139
140
    return args
141
142
143
def init_logging(args):
144
    """
145
    Set the log level according to the -v/-q command line options.
146
    """
147
    log_level = (
148
        logging.FATAL if args.quiet else logging.DEBUG if args.verbose else logging.INFO
149
    )
150
    log_format = '%(message)s'
151
    logging.basicConfig(level=log_level, format=log_format)
152
153
154
def main():
155
    """
156
    Entry point for CLI application.
157
    """
158
    args = parse_arguments()
159
160
    try:
161
        modern.pyclean(args)
162
    except Exception as err:
163
        raise SystemExit(err)
164
    except KeyboardInterrupt:
165
        msg = 'Aborted by user.'
166
        raise SystemExit(msg)
167