Debian Codegraph @

git_delete_merged_branches/_engine.py

raw symbols SCIP
1 # Copyright (C) 2020 Sebastian Pipping <[email protected]>
2 # Licensed under GPL v3 or later
3
4 import os
5 import re
6 from functools import partial, reduce
7 from operator import and_
8 from subprocess import CalledProcessError
9
10 from ._git import CheckoutFailed, MergeBaseFailed, PullFailed
11 from ._metadata import APP
12
13
14 class _DmbException(Exception):
15 pass
16
17
18 class _GitRepositoryWithoutBranches(_DmbException):
19 """
20 Exception for the time between "git init" and the first "git commit"
21 where "git branch" will tell us that there are no branches
22 """
23
24 def __init__(self):
25 super().__init__("This Git repository does not have any branches.")
26
27
28 class _NoSuchBranchException(_DmbException):
29 def __init__(self, branch_name):
30 super().__init__(f"There is no branch {branch_name!r}.")
31
32
33 class _NoSuchRemoteException(_DmbException):
34 def __init__(self, remote_name):
35 super().__init__(f"There is no remote {remote_name!r}.")
36
37
38 class _TooFewOptionsAvailable(_DmbException):
39 pass
40
41
42 class _ZeroMergeTargetsException(_DmbException):
43 def __init__(self):
44 super().__init__("One or more existing target branch is required.")
45
46
47 class _InvalidRegexPattern(_DmbException):
48 def __init__(self, pattern):
49 super().__init__(
50 f'Pattern "{pattern}" is not well-formed regular expression syntax '
51 '(with regard to Python module "re").'
52 )
53
54
55 class _CannotDryRunConfigurationError(_DmbException):
56 def __init__(self, force_reconfiguration):
57 message = (
58 "Arguments --configure and --dry-run are not compatible."
59 if force_reconfiguration
60 else f"{APP}' need for configuration and argument --dry-run are not compatible."
61 )
62 super().__init__(message)
63
64
65 class DeleteMergedBranches:
66 _CONFIG_KEY_CONFIGURED = "delete-merged-branches.configured"
67 _CONFIG_VALUE_CONFIGURED = "5.0.0+" # i.e. most ancient version with compatible config
68 _CONFIG_VALUE_TRUE = "true"
69 _PATTERN_REMOTE_ENABLED = "^remote\\.(?P<name>[^ ]+)\\.dmb-enabled$"
70 _PATTERN_BRANCH_EXCLUDED = "^branch\\.(?P<name>[^ ]+)\\.dmb-excluded$"
71 _PATTERN_BRANCH_REQUIRED = "^branch\\.(?P<name>[^ ]+)\\.dmb-required$"
72 _FORMAT_REMOTE_ENABLED = "remote.{name}.dmb-enabled"
73 _FORMAT_BRANCH_EXCLUDED = "branch.{name}.dmb-excluded"
74 _FORMAT_BRANCH_REQUIRED = "branch.{name}.dmb-required"
75
76 def __init__(self, git, messenger, confirmation, selector, effort_level):
77 self._confirmation = confirmation
78 self._messenger = messenger
79 self._git = git
80 self._selector = selector
81 self._effort_using_git_cherry = effort_level >= 2
82 self._effort_using_squashed_copies = effort_level >= 3
83
84 def _interactively_edit_list(
85 self, description, valid_names, old_names, format, min_selection_count
86 ) -> set[str]:
87 if len(valid_names) < min_selection_count:
88 raise _TooFewOptionsAvailable
89
90 help = (
91 "(Press [Space] to toggle selection, [Enter]/[Return] to accept, [Ctrl]+[C] to quit.)"
92 )
93
94 old_names = set(old_names)
95 initial_selection = [i for i, name in enumerate(valid_names) if name in old_names]
96 if valid_names:
97 new_names = set(
98 self._selector(
99 self._messenger,
100 valid_names,
101 initial_selection,
102 description,
103 help,
104 min_selection_count,
105 )
106 )
107 else:
108 new_names = set()
109 assert len(new_names) >= min_selection_count
110 names_to_remove = old_names - new_names
111 names_to_add = new_names - old_names
112
113 for names, new_value in ((names_to_remove, None), (names_to_add, self._CONFIG_VALUE_TRUE)):
114 for name in names:
115 key = format.format(name=name)
116 self._git.set_config(key, new_value)
117
118 return new_names
119
120 def _configure_required_branches(self, git_config) -> set[str]:
121 try:
122 return self._interactively_edit_list(
123 "[1/3] For a branch to be considered"
124 " fully merged, which other branches"
125 " must it have been merged to?",
126 self._git.find_local_branches(),
127 self.find_required_branches(git_config),
128 self._FORMAT_BRANCH_REQUIRED,
129 min_selection_count=1,
130 )
131 except _TooFewOptionsAvailable:
132 raise _GitRepositoryWithoutBranches
133
134 def _configure_excluded_branches(self, git_config, new_required_branches: set[str]):
135 valid_names = sorted(set(self._git.find_all_branch_names()) - new_required_branches)
136 self._interactively_edit_list(
137 "[2/3] Which of these branches (if any) should be kept around at all times?",
138 valid_names,
139 self.find_excluded_branches(git_config),
140 self._FORMAT_BRANCH_EXCLUDED,
141 min_selection_count=0,
142 )
143
144 def _configure_enabled_remotes(self, git_config):
145 self._interactively_edit_list(
146 "[3/3] Which remotes (if any) do you want to enable deletion of merged branches for?",
147 self._git.find_remotes(),
148 self.find_enabled_remotes(git_config),
149 self._FORMAT_REMOTE_ENABLED,
150 min_selection_count=0,
151 )
152
153 def _configure(self, git_config):
154 repo_basename = os.path.basename(os.getcwd())
155 self._messenger.tell_info(f"Configure {APP} for repository {repo_basename!r}:")
156
157 new_required_branches = self._configure_required_branches(git_config)
158 self._configure_excluded_branches(git_config, new_required_branches)
159 self._configure_enabled_remotes(git_config)
160 self._git.set_config(self._CONFIG_KEY_CONFIGURED, self._CONFIG_VALUE_CONFIGURED)
161
162 @classmethod
163 def _is_configured(cls, git_config):
164 return git_config.get(cls._CONFIG_KEY_CONFIGURED) == cls._CONFIG_VALUE_CONFIGURED
165
166 def ensure_configured(self, force_reconfiguration):
167 git_config = self._git.extract_git_config()
168 if force_reconfiguration or not self._is_configured(git_config):
169 if self._git.pretend:
170 raise _CannotDryRunConfigurationError(force_reconfiguration)
171 self._configure(git_config)
172 git_config = self._git.extract_git_config()
173 assert self._is_configured(git_config)
174 return git_config
175
176 @classmethod
177 def _filter_git_config(cls, git_config, pattern):
178 matcher = re.compile(pattern)
179 matched_names = []
180 for key, value in git_config.items():
181 match = matcher.match(key)
182 if match and value == cls._CONFIG_VALUE_TRUE:
183 matched_names.append(match.group("name"))
184 return matched_names
185
186 @classmethod
187 def find_excluded_branches(cls, git_config):
188 return cls._filter_git_config(git_config, cls._PATTERN_BRANCH_EXCLUDED)
189
190 @classmethod
191 def find_required_branches(cls, git_config):
192 return cls._filter_git_config(git_config, cls._PATTERN_BRANCH_REQUIRED)
193
194 @classmethod
195 def find_enabled_remotes(cls, git_config):
196 return cls._filter_git_config(git_config, cls._PATTERN_REMOTE_ENABLED)
197
198 def _find_branches_merged_using_git_branch_merged(
199 self, required_target_branches, remote_name: str | None
200 ) -> set[str]:
201 if remote_name is None:
202 find_branches_that_were_merged_into = self._git.find_merged_local_branches_for
203 else:
204 find_branches_that_were_merged_into = partial(
205 self._git.find_merged_remote_branches_for, remote_name
206 )
207
208 if len(required_target_branches) == 1:
209 target_branch = next(iter(required_target_branches))
210 branches_merged_to_all_required_targets = set(
211 find_branches_that_were_merged_into(target_branch)
212 )
213 else:
214 branches_merged_to_all_required_targets = reduce(
215 and_,
216 (
217 set(find_branches_that_were_merged_into(target_branch))
218 for target_branch in required_target_branches
219 ),
220 )
221
222 return branches_merged_to_all_required_targets
223
224 def _has_been_squash_merged_into(self, target_branch, topic_branch) -> bool:
225 """
226 Tries to detect a squashed merge, i.e. where a single commit
227 on the target branch pulls in the sum of all commits
228 between the common merge base commit and the tip of the topic branch.
229
230 The implementation creates a temporary squashed copy of those commits
231 and then asks ``git cherry`` if that squashed commit has an equivalent
232 on the target branch.
233 """
234 try:
235 merge_base_commit_sha1 = self._git.merge_base(target_branch, topic_branch)
236 except MergeBaseFailed:
237 return False
238 squash_merge_commit_sha1 = self._git.commit_tree(
239 message=f"Squash-merge {topic_branch!r}",
240 parent_committish=merge_base_commit_sha1,
241 tree=topic_branch + "^{tree}",
242 )
243
244 cherry_lines = self._git.cherry(target_branch, squash_merge_commit_sha1)
245 defacto_merged_into_target = all(line.startswith("-") for line in cherry_lines)
246 return defacto_merged_into_target
247
248 def _find_branches_merged_using_git_cherry(
249 self, required_target_branches, candidate_branches
250 ) -> set[str]:
251 assert required_target_branches
252
253 if not candidate_branches:
254 return set()
255
256 branches_merged_to_all_required_targets = set()
257 candidates_for_squashed_merges = []
258
259 for topic_branch in sorted(candidate_branches):
260 assert topic_branch not in required_target_branches
261
262 for target_branch in sorted(required_target_branches):
263 cherry_lines = self._git.cherry(target_branch, topic_branch)
264 defacto_merged_into_target = all(line.startswith("-") for line in cherry_lines)
265 if not defacto_merged_into_target:
266 if len(cherry_lines) > 1:
267 candidates_for_squashed_merges.append(topic_branch)
268 break
269 else: # i.e. no break happened above
270 branches_merged_to_all_required_targets.add(topic_branch)
271
272 if self._effort_using_squashed_copies:
273 check_for_squash_merges = True
274
275 if candidates_for_squashed_merges:
276 if self._git.has_detached_heads():
277 self._messenger.tell_info(
278 "Skipped further inspection of branches because of detached HEAD."
279 )
280 check_for_squash_merges = False
281
282 if check_for_squash_merges:
283 if self._git.has_uncommitted_changes():
284 self._messenger.tell_info(
285 "Skipped further inspection of branches due to uncommitted changes."
286 )
287 check_for_squash_merges = False
288
289 if check_for_squash_merges:
290 for topic_branch in candidates_for_squashed_merges:
291 for target_branch in sorted(required_target_branches):
292 defacto_merged_into_target = self._has_been_squash_merged_into(
293 target_branch=target_branch, topic_branch=topic_branch
294 )
295 if not defacto_merged_into_target:
296 break
297 else: # i.e. no break happened above
298 branches_merged_to_all_required_targets.add(topic_branch)
299
300 return branches_merged_to_all_required_targets
301
302 def _find_branches_merged_to_all_targets_for_single_remote(
303 self, required_target_branches, excluded_branches: set[str], remote_name: str | None
304 ) -> tuple[set[str], set[str]]:
305 if remote_name is not None:
306 excluded_branches = {
307 f"{remote_name}/{branch_name}" for branch_name in excluded_branches
308 }
309
310 truly_merged_branches = (
311 self._find_branches_merged_using_git_branch_merged(
312 required_target_branches, remote_name=remote_name
313 )
314 ) - excluded_branches
315
316 if self._effort_using_git_cherry:
317 if remote_name is None:
318 all_branches_at_remote = set(self._git.find_local_branches())
319 else:
320 all_branches_at_remote = set(self._git.find_remote_branches_at(remote_name))
321 if remote_name is not None:
322 required_target_branches = {
323 f"{remote_name}/{branch_name}" for branch_name in required_target_branches
324 }
325 branches_to_inspect_using_git_cherry = (
326 all_branches_at_remote
327 - required_target_branches
328 - excluded_branches
329 - truly_merged_branches
330 )
331 defacto_merged_branches = self._find_branches_merged_using_git_cherry(
332 required_target_branches, branches_to_inspect_using_git_cherry
333 )
334 else:
335 defacto_merged_branches = set()
336
337 return (truly_merged_branches, defacto_merged_branches)
338
339 def _report_branches_as_deleted(self, branch_names: set[str], remote_name: str = None):
340 branch_type = "local" if (remote_name is None) else "remote"
341 info_text = f"{len(branch_names)} {branch_type} branch(es) deleted."
342 self._messenger.tell_info(info_text)
343
344 def _delete_local_merged_branches_for(self, required_target_branches, excluded_branches):
345 for working_tree_branch in self._git.find_working_tree_branches():
346 branch_would_be_analyzed = (
347 working_tree_branch is not None
348 and working_tree_branch not in required_target_branches
349 and working_tree_branch not in excluded_branches
350 )
351 if branch_would_be_analyzed:
352 excluded_branches = excluded_branches | {working_tree_branch}
353 self._messenger.tell_info(
354 f"Skipped branch {working_tree_branch!r} because it is currently checked out."
355 )
356
357 truly_merged, defacto_merged = self._find_branches_merged_to_all_targets_for_single_remote(
358 required_target_branches, excluded_branches, remote_name=None
359 )
360
361 local_branches_to_delete = truly_merged | defacto_merged
362
363 if not local_branches_to_delete:
364 self._messenger.tell_info("No local branches deleted.")
365 return
366
367 description = (
368 f"You are about to delete {len(local_branches_to_delete)}"
369 " local branch(es):\n"
370 + "\n".join(f" - {name}" for name in sorted(local_branches_to_delete))
371 + "\n\nDelete?"
372 )
373 if not self._confirmation.confirmed(description):
374 return
375
376 # NOTE: With regard to reporting, the idea is to
377 # - report all deleted local branches at once when deletion was successful, and to
378 # - not silence partial success
379 # when the first delete call was successful and the second call was not.
380 self._git.delete_local_branches(truly_merged)
381 try:
382 self._git.delete_local_branches(defacto_merged, force=True)
383 except CalledProcessError:
384 self._report_branches_as_deleted(truly_merged)
385 raise
386 else:
387 self._report_branches_as_deleted(truly_merged | defacto_merged)
388
389 def _delete_remote_merged_branches_for(
390 self, required_target_branches, excluded_branches, remote_name, all_branch_refs: set[str]
391 ):
392 if not all(
393 (f"{remote_name}/{branch_name}" in all_branch_refs)
394 for branch_name in required_target_branches
395 ):
396 self._messenger.tell_info(
397 f"Skipped remote {remote_name!r} as it does not have all required branches."
398 )
399 return
400
401 truly_merged, defacto_merged = self._find_branches_merged_to_all_targets_for_single_remote(
402 required_target_branches, excluded_branches, remote_name=remote_name
403 )
404 remote_branches_to_delete = [
405 b for b in (truly_merged | defacto_merged) if b.startswith(f"{remote_name}/")
406 ]
407
408 if not remote_branches_to_delete:
409 self._messenger.tell_info("No remote branches deleted.")
410 return
411
412 description = (
413 f"You are about to delete {len(remote_branches_to_delete)} "
414 "remote branch(es):\n"
415 + "\n".join(f" - {name}" for name in sorted(remote_branches_to_delete))
416 + "\n\nDelete?"
417 )
418 if not self._confirmation.confirmed(description):
419 return
420
421 self._git.delete_remote_branches(remote_branches_to_delete, remote_name)
422 self._report_branches_as_deleted(remote_branches_to_delete, remote_name)
423
424 def refresh_remotes(self, enabled_remotes):
425 sorted_remotes = sorted(set(enabled_remotes))
426 if not sorted_remotes:
427 return
428
429 description = (
430 f'Do you want to run "git remote update --prune"'
431 f" for {len(sorted_remotes)} remote(s):\n"
432 + "\n".join(f" - {name}" for name in sorted_remotes)
433 + "\n\nUpdate?"
434 )
435 if not self._confirmation.confirmed(description):
436 return
437
438 for remote_name in sorted_remotes:
439 self._git.update_and_prune_remote(remote_name)
440
441 def detect_stale_remotes(self, enabled_remotes, required_target_branches):
442 sorted_remotes = sorted(set(enabled_remotes))
443 if not sorted_remotes:
444 return
445
446 sorted_required_target_branches = sorted(set(required_target_branches))
447 assert sorted_required_target_branches
448
449 for remote_name in enabled_remotes:
450 remote_branches = set(self._git.find_remote_branches_at(remote_name))
451 not_fully_pushed_branches = [
452 branch
453 for branch in sorted_required_target_branches
454 if f"{remote_name}/{branch}" in remote_branches
455 and self._git.has_unpushed_commits_on(
456 branch, with_regard_to=f"{remote_name}/{branch}"
457 )
458 ]
459
460 if not_fully_pushed_branches:
461 self._messenger.tell_info(
462 (
463 f"Remote {remote_name!r} is not up to date with"
464 f" {len(not_fully_pushed_branches)} local"
465 " branch(es):\n"
466 )
467 + "\n".join(f" - {branch}" for branch in not_fully_pushed_branches)
468 + (
469 "\n\nThis will likely impair detection"
470 f" of merged branches for remote {remote_name!r}."
471 "\nPlease consider getting it back in sync"
472 " by running\n"
473 )
474 + "\n".join(
475 f" $ git push {remote_name} {branch}"
476 for branch in not_fully_pushed_branches
477 )
478 + f"\n\nand then invoking {APP}, again."
479 )
480
481 def refresh_target_branches(self, required_target_branches):
482 sorted_branches = sorted(set(required_target_branches))
483 if not sorted_branches:
484 return
485
486 initial_branch = self._git.find_current_branch()
487 if initial_branch is None or self._git.has_detached_heads():
488 self._messenger.tell_info("Skipped refreshing branches because of detached HEAD.")
489 return
490
491 if self._git.has_uncommitted_changes():
492 self._messenger.tell_info("Skipped refreshing branches due to uncommitted changes.")
493 return
494
495 description = (
496 f'Do you want to run "git pull --ff-only"'
497 f" for {len(sorted_branches)} branch(es):\n"
498 + "\n".join(f" - {name}" for name in sorted_branches)
499 + "\n\nPull?"
500 )
501 if not self._confirmation.confirmed(description):
502 return
503
504 needs_a_switch_back = False
505 try:
506 for branch_name in sorted_branches:
507 if branch_name != initial_branch:
508 try:
509 self._git.checkout(branch_name)
510 except CheckoutFailed:
511 self._messenger.tell_error(
512 f"Refreshing local branch {branch_name!r}"
513 " failed"
514 " because the branch cannot be checkout out."
515 )
516 continue
517 needs_a_switch_back = True
518
519 try:
520 self._git.pull_ff_only()
521 except PullFailed:
522 self._messenger.tell_error(
523 f"Refreshing local branch {branch_name!r} failed"
524 " because the branch cannot be pulled"
525 " with fast forward."
526 )
527 finally:
528 if needs_a_switch_back:
529 self._git.checkout(initial_branch)
530
531 def delete_merged_branches(self, required_target_branches, excluded_branches, enabled_remotes):
532 self._delete_local_merged_branches_for(required_target_branches, excluded_branches)
533 all_branch_refs = set(self._git.find_all_branch_refs())
534 for remote_name in enabled_remotes:
535 self._delete_remote_merged_branches_for(
536 required_target_branches, excluded_branches, remote_name, all_branch_refs
537 )
538
539 def determine_excluded_branches(
540 self, git_config: dict, excluded_branches: list[str], included_branches_patterns: list[str]
541 ) -> set[str]:
542 existing_branches = set(self._git.find_all_branch_names())
543 if excluded_branches:
544 excluded_branches_set = set(excluded_branches)
545 invalid_branches = excluded_branches_set - existing_branches
546 if invalid_branches:
547 raise _NoSuchBranchException(sorted(invalid_branches)[0])
548 else:
549 excluded_branches_set = set()
550
551 excluded_branches_set |= set(self.find_excluded_branches(git_config)) & existing_branches
552
553 # The inclusion patterns are meant to work in logical conjunction ("and") but an empty
554 # list should not exclude any branches. So we'll add any existing branch to the exclusion
555 # set that fails to match any of the inclusion patterns:
556 for included_branches_pattern in included_branches_patterns:
557 try:
558 matcher = re.compile(included_branches_pattern)
559 except re.error:
560 raise _InvalidRegexPattern(included_branches_pattern)
561
562 for branch_name in existing_branches:
563 if matcher.search(branch_name):
564 continue
565 excluded_branches_set.add(branch_name)
566
567 return excluded_branches_set
568
569 def determine_required_target_branches(
570 self, git_config: dict, required_target_branches: list[str]
571 ):
572 existing_branches = set(self._git.find_local_branches())
573 if required_target_branches:
574 required_target_branches_set = set(required_target_branches)
575 invalid_branches = required_target_branches_set - existing_branches
576 if invalid_branches:
577 raise _NoSuchBranchException(required_target_branches[0])
578 else:
579 required_target_branches_set = (
580 set(self.find_required_branches(git_config)) & existing_branches
581 )
582
583 if not required_target_branches_set:
584 raise _ZeroMergeTargetsException
585
586 return required_target_branches_set
587
588 def determine_enabled_remotes(self, git_config: dict, enabled_remotes: list[str]):
589 existing_remotes = set(self._git.find_remotes())
590 if enabled_remotes:
591 enabled_remotes_set = set(enabled_remotes)
592 invalid_remotes = enabled_remotes_set - existing_remotes
593 if invalid_remotes:
594 raise _NoSuchRemoteException(enabled_remotes[0])
595 return enabled_remotes_set
596 else:
597 return set(self.find_enabled_remotes(git_config)) & existing_remotes