Coverage for src/tools/git_pu.py: 24.10%
166 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-07 23:52 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-07 23:52 +0000
1#!/usr/bin/env python3
2# PYTHON_ARGCOMPLETE_OK
4# Standard libraries
5from argparse import (
6 _ArgumentGroup,
7 ArgumentParser,
8 Namespace,
9 RawTextHelpFormatter,
10)
11from shutil import get_terminal_size
12from sys import exit as sys_exit
13from time import sleep
14from typing import List, Optional
16# Modules libraries
17from argcomplete import autocomplete
18from questionary import (
19 confirm as questionary_confirm,
20 press_any_key_to_continue as questionary_press_any_key_to_continue,
21)
23# Components
24from ..package.bundle import Bundle
25from ..package.settings import Settings
26from ..package.updates import Updates
27from ..prints.colors import Colors
28from ..system.platform import Platform
29from .git_stat import git_stat
30from .tools import Tools
32# Constants
33HELP_POSITION: int = 23
35# Git push, pylint: disable=duplicate-code,too-many-arguments,too-many-branches,too-many-positional-arguments,too-many-return-statements,too-many-statements
36def git_pu(
37 remote: str,
38 reference: str,
39 tags: bool,
40 no_verify: bool,
41 ref: str,
42 force: bool,
43 confirmation: Optional[bool] = None,
44) -> int:
46 # Variables
47 commands: List[str]
48 result: int
49 risky: bool = False
51 # Select remote
52 if not remote:
53 remote = Tools.select_remote()
55 # Validate remote
56 if not remote:
57 print(' ')
58 print(f'{Colors.YELLOW} {Tools.NAME}:'
59 f'{Colors.RED} Remote selection missing...'
60 f'{Colors.RESET}')
61 print(' ')
62 Platform.flush()
63 return -1
65 # Select branch
66 if not tags and not reference:
67 reference = Tools.select_branch(remote)
69 # Validate branch
70 if not reference:
71 print(' ')
72 print(f'{Colors.YELLOW} {Tools.NAME}:'
73 f'{Colors.RED} Remote branch selection missing...'
74 f'{Colors.RESET}')
75 print(' ')
76 Platform.flush()
77 return -2
79 # Push header
80 push_target: str
81 if tags and reference:
82 push_target = f'tag {reference}'
83 elif tags:
84 push_target = 'tags'
85 else:
86 push_target = f"branch '{reference}'"
87 print(' ')
88 print(f'{Colors.GREEN} === {Tools.NAME} - Pushing'
89 f' {push_target}'
90 f' to remote \'{remote}\' ==='
91 f'{Colors.RESET}')
92 Platform.flush()
94 # Show tags differences
95 if tags:
96 print(' ')
97 commands = [
98 'git',
99 'push',
100 '--dry-run',
101 ]
102 if no_verify:
103 commands += [
104 '--no-verify',
105 ]
106 if not reference:
107 commands += [
108 '--tags',
109 ]
110 commands += [
111 remote,
112 ]
113 if reference:
114 commands += [
115 'tag',
116 reference,
117 ]
118 result = Tools.run_command(commands)
119 print(' ')
120 Platform.flush()
122 # Confirm tags overwrite
123 if result != 0:
124 risky = True
125 print(
126 f'{Colors.YELLOW} {Tools.NAME}:'
127 f'{Colors.RED} Older tags will be lost on the remote. Continue ?'
128 f'{Colors.RESET} [Enter]'
129 f'{Colors.RESET}',
130 end='',
131 )
132 Platform.flush()
133 if confirmation is True and (not risky or force):
134 print(' (Confirmed by argument)')
135 Platform.flush()
136 sleep(1)
137 elif confirmation is False:
138 return -3
139 elif questionary_press_any_key_to_continue(
140 message='',
141 style=None,
142 ).ask() is None:
143 print(' ')
144 return -3
145 print(' ')
146 Platform.flush()
148 # Show git statistics
149 else:
150 _, commits_remote = git_stat(
151 remote=remote,
152 reference=reference,
153 compare=ref,
154 stats_only=True,
155 )
156 if commits_remote > 0:
157 risky = True
158 print(
159 f'{Colors.YELLOW} {Tools.NAME}:'
160 f'{Colors.RED} {commits_remote} commit{"s" if commits_remote > 1 else ""}'
161 ' will be lost on the remote. Continue ?'
162 f'{Colors.RESET} [Enter]'
163 f'{Colors.RESET}',
164 end='',
165 )
166 Platform.flush()
167 if confirmation is True and (not risky or force):
168 print(' (Confirmed by argument)')
169 Platform.flush()
170 sleep(1)
171 elif confirmation is False:
172 return -4
173 elif questionary_press_any_key_to_continue(
174 message='',
175 style=None,
176 ).ask() is None:
177 print(' ')
178 return -4
179 print(' ')
180 Platform.flush()
182 # Prepare push commands
183 commands = [
184 'git',
185 'push',
186 ]
188 # Configure force option
189 if force or risky:
190 commands += [
191 '--force',
192 ]
194 # Configure verify option
195 if no_verify:
196 commands += [
197 '--no-verify',
198 ]
200 # Configure tags option
201 if tags and not reference:
202 commands += [
203 '--tags',
204 ]
206 # Configure remote argument
207 commands += [
208 remote,
209 ]
211 # Configure reference arguments
212 if tags and reference:
213 commands += [
214 'tag',
215 reference,
216 ]
217 elif not tags:
218 commands += [
219 f'{ref}:refs/heads/{reference}',
220 ]
222 # Confirm push to remote
223 try:
224 print(
225 f'{Colors.YELLOW} {Tools.NAME}:'
226 f'{Colors.RED_THIN if risky else Colors.GREEN_THIN} {" ".join(commands)}'
227 f'{Colors.RED if risky else Colors.GREEN} # Update'
228 f'{Colors.RESET}',
229 end='',
230 )
231 if confirmation is True and (not risky or force):
232 print(' (Confirmed by argument)')
233 Platform.flush()
234 sleep(1)
235 elif confirmation is False:
236 print(' (Canceled by argument)')
237 print(' ')
238 Platform.flush()
239 sleep(1)
240 return 0
241 elif not questionary_confirm(
242 message='',
243 default=not risky,
244 qmark='',
245 style=None,
246 auto_enter=True,
247 ).ask():
248 print(' ')
249 Platform.flush()
250 return 0
252 # Selector interruption
253 except KeyboardInterrupt:
254 print(' ')
255 Platform.flush()
256 return -5
258 # Push to remote
259 print(' ')
260 result = Tools.run_command(commands)
261 print(' ')
262 Platform.flush()
264 # Result
265 return result
267# Main, pylint: disable=duplicate-code
268def main() -> None:
270 # Variables
271 confirmation: Optional[bool]
272 group: _ArgumentGroup
273 result: int
275 # Configure tool
276 Tools.NAME = 'git pu'
277 Tools.DESCRIPTION = 'Git push with interactive selection'
279 # Arguments creation
280 parser: ArgumentParser = ArgumentParser(
281 prog=Tools.NAME,
282 description=f'{Tools.NAME}: {Tools.DESCRIPTION} ({Bundle.NAME})',
283 add_help=False,
284 formatter_class=lambda prog: RawTextHelpFormatter(
285 prog,
286 max_help_position=HELP_POSITION,
287 width=min(
288 120,
289 get_terminal_size().columns - 2,
290 ),
291 ),
292 )
294 # Arguments tool definitions
295 group = parser.add_argument_group('tool arguments')
296 group.add_argument(
297 '-h',
298 '--help',
299 dest='help',
300 action='store_true',
301 help='Show this help message',
302 )
303 group.add_argument(
304 '-f',
305 '--force',
306 dest='force',
307 action='store_true',
308 help='Force push changes',
309 )
310 group.add_argument(
311 '-r',
312 '--ref',
313 dest='ref',
314 action='store',
315 default='HEAD',
316 help='Reference to push (default: %(default)s)',
317 )
318 group.add_argument(
319 '-t',
320 '--tags',
321 dest='tags',
322 action='store_true',
323 help='Push tags instead of branches',
324 )
325 group.add_argument(
326 '--all',
327 dest='all',
328 action='store_true',
329 help='Iterate over available remotes and branches',
330 )
331 group.add_argument(
332 '--no-verify',
333 dest='no_verify',
334 action='store_true',
335 help='Disable pre-commit \'pre-push\' hooks',
336 )
337 group.add_argument(
338 '--validate',
339 dest='validate',
340 action='store_true',
341 help='Validate result by requesting user input',
342 )
343 group.add_argument(
344 '-y',
345 '--yes',
346 dest='yes',
347 action='store_true',
348 help='Automatic yes to user inputs',
349 )
350 group.add_argument(
351 '-n',
352 '--no',
353 dest='no',
354 action='store_true',
355 help='Automatic no to user inputs',
356 )
357 group.add_argument(
358 'remote',
359 nargs='?',
360 default=None,
361 help='Remote repository name (default: auto)',
362 )
363 group.add_argument(
364 'reference',
365 nargs='?',
366 default=None,
367 help='Branch or tag reference name (default: auto)',
368 )
370 # Arguments autocompletion
371 autocomplete(parser)
373 # Arguments parser
374 options: Namespace = parser.parse_args()
376 # Help informations
377 if options.help:
378 print(' ')
379 parser.print_help()
380 print(' ')
381 Platform.flush()
382 sys_exit(0)
384 # Instantiate settings
385 settings: Settings = Settings(name=Bundle.NAME)
387 # Prepare colors
388 Colors.prepare()
390 # Instantiate updates
391 updates: Updates = Updates(
392 name=Bundle.PACKAGE,
393 settings=settings,
394 )
396 # Prepare confirmation
397 if options.no:
398 confirmation = False
399 elif options.yes:
400 confirmation = True
401 else:
402 confirmation = None
404 # Iterate over remotes
405 for remote in Tools.git_remotes() if options.all else [
406 options.remote,
407 ]:
409 # Iterate over references
410 for reference in Tools.git_branches(remote) if options.all else [
411 options.reference,
412 ]:
414 # Run tool
415 result = git_pu(
416 remote=remote,
417 reference=reference,
418 force=options.force,
419 no_verify=options.no_verify,
420 ref=options.ref,
421 tags=options.tags,
422 confirmation=confirmation,
423 )
425 # Validate result
426 if result < 0:
427 break
429 # Check for daily updates
430 if updates.enabled and updates.daily:
431 updates.check()
433 # Validate result
434 if options.validate and not options.yes:
435 print(
436 f'{Colors.YELLOW} {Tools.NAME}:'
437 f'{Colors.GREEN if result >= 0 else Colors.RED} Press any key to continue...'
438 f'{Colors.RESET} [Enter]'
439 f'{Colors.RESET}',
440 end='',
441 )
442 questionary_press_any_key_to_continue(
443 message='',
444 style=None,
445 ).ask()
446 print(' ')
448 # Result
449 sys_exit(0 if result >= 0 else result)
451# Entrypoint
452if __name__ == '__main__': # pragma: no cover
453 main()