Debian Codegraph @

git_delete_merged_branches/_cli.py

raw symbols SCIP
1 # Copyright (C) 2020 Sebastian Pipping <[email protected]>
2 # Licensed under GPL v3 or later
3
4 import argparse
5 import os
6 import sys
7 import traceback
8 from argparse import RawDescriptionHelpFormatter
9 from functools import partial
10 from signal import SIGINT
11 from subprocess import CalledProcessError
12 from textwrap import dedent
13
14 import colorama
15
16 from ._argparse_color import add_color_to_formatter_class
17 from ._confirm import Confirmation
18 from ._engine import DeleteMergedBranches
19 from ._git import Git
20 from ._messenger import Messenger
21 from ._metadata import APP, DESCRIPTION, VERSION
22 from ._multiselect import multiselect
23
24
25 def _parse_command_line(colorize: bool, args=None):
26 _EPILOG = dedent(f"""\
27 Software libre licensed under GPL v3 or later.
28 Brought to you by Sebastian Pipping <[email protected]>.
29
30 Please report bugs at https://github.com/hartwork/{APP} — thank you!
31 """)
32
33 if args is None:
34 args = sys.argv[1:]
35
36 formatter_class = RawDescriptionHelpFormatter
37 if colorize:
38 formatter_class = add_color_to_formatter_class(formatter_class)
39
40 prog = os.path.basename(sys.argv[0])
41
42 parser_kwargs = dict(
43 prog=prog,
44 add_help=False,
45 description=DESCRIPTION,
46 epilog=_EPILOG,
47 formatter_class=formatter_class,
48 )
49
50 # The enabled-by-default color in Python >=3.14
51 # (https://github.com/python/cpython/issues/130645) is nice but
52 # breaks git-dmb's own coloring, so we disable their coloring.
53 # Keyword "color" does not exist prior to Python 3.14.
54 if sys.version_info >= (3, 14):
55 parser_kwargs["color"] = False
56
57 parser = argparse.ArgumentParser(**parser_kwargs)
58
59 modes = parser.add_argument_group("modes").add_mutually_exclusive_group()
60 modes.add_argument(
61 "--configure",
62 dest="force_reconfiguration",
63 action="store_true",
64 help=f"configure {APP} and exit (without processing any branches)",
65 )
66 modes.add_argument("--help", "-h", action="help", help="show this help message and exit")
67 modes.add_argument("--version", action="version", version="%(prog)s " + VERSION)
68
69 rules = parser.add_argument_group("rules")
70 rules.add_argument(
71 "--branch",
72 "-b",
73 metavar="BRANCH",
74 dest="required_target_branches",
75 default=[],
76 action="append",
77 help="require the given branch as a merge target (instead of what is"
78 " configured for this repository); can be passed multiple times",
79 )
80 rules.add_argument(
81 "--effort",
82 metavar="LEVEL",
83 dest="effort_level",
84 type=int,
85 default=2,
86 choices=[1, 2, 3],
87 help=(
88 "level of effort to put into finding merged branches"
89 '; level 1 uses nothing but "git branch --merged"'
90 ', level 2 adds use of "git cherry"'
91 ', level 3 adds use of "git cherry" on temporary squashed copies'
92 " (default level: %(default)d)"
93 ),
94 )
95
96 scope = parser.add_argument_group("scope")
97 scope.add_argument(
98 "--remote",
99 "-r",
100 metavar="REMOTE",
101 dest="enabled_remotes",
102 default=[],
103 action="append",
104 help=(
105 "process the given remote (instead of the remotes that are"
106 " configured for this repository); can be passed multiple times"
107 ),
108 )
109 scope.add_argument(
110 "--exclude",
111 "-x",
112 metavar="BRANCH",
113 dest="excluded_branches",
114 default=[],
115 action="append",
116 help=(
117 "exclude the given branch from deletion (in addition to"
118 " the exclusion list that is configured for this repository)"
119 "; can be passed multiple times"
120 ),
121 )
122 scope.add_argument(
123 "--include-regex",
124 metavar="PATTERN",
125 dest="included_branches_patterns",
126 default=[],
127 action="append",
128 help=(
129 "only consider branches for deletion that match the given"
130 ' regular expression (e.g. "^issue-")'
131 '; syntax is that of Python module "re"'
132 "; can be passed multiple times"
133 ', then acts in logical conjunction ("and")'
134 ),
135 )
136
137 switches = parser.add_argument_group("flags")
138 switches.add_argument(
139 "--debug", dest="debug", action="store_true", help="enable debugging output"
140 )
141 switches.add_argument(
142 "--dry-run",
143 "-n",
144 dest="pretend",
145 action="store_true",
146 help="perform a trial run with no changes made",
147 )
148 switches.add_argument(
149 "--verbose", "-v", dest="verbose", action="store_true", help="enable verbose output"
150 )
151 switches.add_argument(
152 "--yes",
153 "-y",
154 dest="ask",
155 default=True,
156 action="store_false",
157 help='do not ask for confirmation, assume reply "yes"',
158 )
159
160 return parser.parse_args(args)
161
162
163 def _innermost_main(config, messenger, colorize: bool):
164 git = Git(messenger, pretend=config.pretend, verbose=config.verbose)
165 confirmation = Confirmation(messenger, ask=config.ask)
166 selector = partial(multiselect, colorize=colorize)
167
168 dmb = DeleteMergedBranches(git, messenger, confirmation, selector, config.effort_level)
169
170 git_config = dmb.ensure_configured(config.force_reconfiguration)
171 if config.force_reconfiguration:
172 return
173
174 required_target_branches = dmb.determine_required_target_branches(
175 git_config, config.required_target_branches
176 )
177 excluded_branches = dmb.determine_excluded_branches(
178 git_config, config.excluded_branches, config.included_branches_patterns
179 )
180 enabled_remotes = dmb.determine_enabled_remotes(git_config, config.enabled_remotes)
181
182 dmb.refresh_remotes(enabled_remotes)
183 dmb.detect_stale_remotes(enabled_remotes, required_target_branches)
184 dmb.refresh_target_branches(required_target_branches)
185 dmb.delete_merged_branches(required_target_branches, excluded_branches, enabled_remotes)
186
187
188 def _inner_main():
189 colorize = "NO_COLOR" not in os.environ
190 if colorize:
191 colorama.init()
192
193 messenger = Messenger(colorize=colorize)
194
195 config = _parse_command_line(colorize=colorize)
196 try:
197 _innermost_main(config, messenger, colorize)
198 except CalledProcessError as e:
199 # Produce more human-friendly output than str(e)
200 message = f"Command '{' '.join(e.cmd)}' returned non-zero exit status {e.returncode}."
201 messenger.tell_error(message)
202 sys.exit(1)
203 except Exception as e:
204 if config.debug:
205 traceback.print_exc()
206 messenger.tell_error(str(e))
207 sys.exit(1)
208
209
210 def main():
211 try:
212 _inner_main()
213 except KeyboardInterrupt:
214 sys.exit(128 + SIGINT)