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

pyclean.gitclean   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 23
dl 0
loc 43
rs 10
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
A build_git_clean_command() 0 9 3
A execute_git_clean() 0 17 3
1
# SPDX-FileCopyrightText: 2020 Peter Bittner <[email protected]>
2
#
3
# SPDX-License-Identifier: GPL-3.0-or-later
4
5
"""Git integration for cleaning untracked files."""
6
7
import logging
8
import subprocess
9
10
GIT_FATAL_ERROR = 128
11
12
log = logging.getLogger(__name__)
13
14
15
def build_git_clean_command(
16
    ignore_patterns: list[str],
17
    dry_run=False,
18
    force=False,
19
) -> list[str]:
20
    """Build the git clean command with appropriate flags."""
21
    exclude = (item for pattern in ignore_patterns for item in ['-e', pattern])
22
    mode = '-n' if dry_run else '-f' if force else '-i'
23
    return ['git', 'clean', '-dx', *exclude, mode]
24
25
26
def execute_git_clean(directory, args):
27
    """
28
    Execute git clean in the specified directory.
29
    """
30
    log.info('Executing git clean...')
31
    cmd = build_git_clean_command(args.ignore, dry_run=args.dry_run, force=args.yes)
32
33
    log.debug('Run: %s', ' '.join(cmd))
34
    result = subprocess.run(cmd, cwd=directory, check=False)  # noqa: S603
35
36
    if result.returncode == GIT_FATAL_ERROR:
37
        log.warning(
38
            'Directory %s is not under version control. Skipping git clean.',
39
            directory,
40
        )
41
    elif result.returncode:
42
        raise SystemExit(result.returncode)
43