| Total Complexity | 6 |
| Total Lines | 45 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 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 | """ |
||
| 21 | Build the git clean command with appropriate flags. |
||
| 22 | """ |
||
| 23 | exclude = (item for pattern in ignore_patterns for item in ['-e', pattern]) |
||
|
|
|||
| 24 | mode = '-n' if dry_run else '-f' if force else '-i' |
||
| 25 | return ['git', 'clean', '-dx', *exclude, mode] |
||
| 26 | |||
| 27 | |||
| 28 | def execute_git_clean(directory, args): |
||
| 29 | """ |
||
| 30 | Execute git clean in the specified directory. |
||
| 31 | """ |
||
| 32 | log.info('Executing git clean...') |
||
| 33 | cmd = build_git_clean_command(args.ignore, dry_run=args.dry_run, force=args.yes) |
||
| 34 | |||
| 35 | log.debug('Run: %s', ' '.join(cmd)) |
||
| 36 | result = subprocess.run(cmd, cwd=directory, check=False) # noqa: S603 |
||
| 37 | |||
| 38 | if result.returncode == GIT_FATAL_ERROR: |
||
| 39 | log.warning( |
||
| 40 | 'Directory %s is not under version control. Skipping git clean.', |
||
| 41 | directory, |
||
| 42 | ) |
||
| 43 | elif result.returncode: |
||
| 44 | raise SystemExit(result.returncode) |
||
| 45 |