Coverage for src/tools/git_dashboard_panel.py: 31.03%
174 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 _MutuallyExclusiveGroup,
8 ArgumentParser,
9 Namespace,
10 RawTextHelpFormatter,
11)
12from os import (
13 environ,
14 getcwd,
15 linesep,
16 path,
17)
18from pathlib import Path
19from shutil import get_terminal_size, which
20from sys import exit as sys_exit
21from time import sleep
22from typing import List
24# Modules libraries
25from argcomplete import autocomplete
27# Components
28from ..package.bundle import Bundle
29from ..package.settings import Settings
30from ..package.updates import Updates
31from ..prints.colors import Colors
32from ..system.platform import Platform
33from .tools import Tools
35# Constants
36BINARY_BYOBU: str = 'byobu'
37BINARY_FZF: str = 'fzf'
38BINARY_SCREEN: str = 'screen'
39BINARY_TMUX: str = 'tmux'
40CONFIGURATION_PATH: str = 'dashboard-panel.conf'
41HELP_POSITION: int = 26
42LABEL_CONFIGURE: str = 'Configure dashboard'
43LABEL_EXIT: str = 'Exit dashboard'
44LABEL_RELOAD: str = 'Reload dashboard'
45SEPARATOR_SHORT: str = '────────────────────────'
46SEPARATOR_LONG: str = '────────────────────────────────────────────────'
48# Open path
49def open_path(selection: str, tabs: bool = False) -> int:
51 # Variables
52 name: str = path.basename(selection)
53 multiplexers: List[str]
55 # Align split
56 terminal = get_terminal_size()
57 split: str = '-v'
58 if terminal.lines < terminal.columns / 6:
59 split = '-h'
61 # Open byobu panel
62 if which(BINARY_BYOBU):
63 if tabs:
64 return Tools.run_command([
65 BINARY_BYOBU,
66 'split-window',
67 '-c',
68 selection,
69 split,
70 ])
71 return Tools.run_command([
72 BINARY_BYOBU,
73 'new-window',
74 '-c',
75 selection,
76 '-n',
77 name,
78 ])
80 # Open tmux panel
81 if which(BINARY_TMUX):
82 if tabs:
83 return Tools.run_command([
84 BINARY_TMUX,
85 'split-window',
86 '-c',
87 selection,
88 split,
89 ])
90 return Tools.run_command([
91 BINARY_TMUX,
92 'new-window',
93 '-c',
94 selection,
95 '-n',
96 name,
97 ])
99 # Open screen panel
100 if which(BINARY_SCREEN):
101 return Tools.run_command([
102 BINARY_SCREEN,
103 '-t',
104 name,
105 selection,
106 ])
108 # Missing multiplexer support
109 multiplexers = [
110 BINARY_BYOBU,
111 BINARY_SCREEN,
112 BINARY_TMUX,
113 ]
114 print(' ')
115 print(f'{Colors.YELLOW} {Tools.NAME}:'
116 f'{Colors.RED} No supported terminal multiplexer detected'
117 f'{Colors.CYAN} (Supported: {", ".join(multiplexers)})'
118 f'{Colors.RESET}')
119 print(' ')
120 Platform.flush()
121 sleep(3)
122 return -1
124# Provide fzf preview command
125def provide_fzf_preview(configuration: str, ) -> str:
127 # Variables
128 fzf_file = '{}'
130 # Provide command
131 return f'''
132 if [ -d {fzf_file} ]; then
133 ls -lah --color=always {fzf_file};
134 elif [ -f {fzf_file} ]; then
135 cat {fzf_file};
136 elif [ {fzf_file} = "{LABEL_CONFIGURE}" ]; then
137 cat {configuration};
138 fi
139 '''
141# Provide fzf reload command
142def provide_fzf_reload(
143 presets: bool,
144 configuration: str,
145 depth: int,
146 discover: bool,
147 differences: bool,
148) -> str:
150 # Variables
151 section_discover: str = ''
152 section_options: str = ''
153 section_presets: str = ''
154 section_separator: str = ''
156 # Prepare options
157 if presets and discover:
158 section_options += f"""
159 echo '{LABEL_RELOAD}';
160 echo '{LABEL_CONFIGURE}';
161 echo '{LABEL_EXIT}';
162 echo '{SEPARATOR_SHORT}';
163 """
165 # Enable presets
166 if presets:
167 section_presets = f"""
168 sed \
169 -e 's|^~/|{environ.get("HOME", "")}/|' \
170 -e 's/^$/{SEPARATOR_SHORT}/' \
171 '{configuration}';
172 """
174 # Enable discovery with differences
175 if discover and differences:
176 section_discover = f"""
177 find \
178 -maxdepth '{depth}' \
179 -name '.git' \
180 -not -path '*/.cache/*' \
181 -not -path '*/build/*' \
182 -exec sh -c 'git -C "$(dirname "{{{{}}}}")" status --porcelain \
183 | grep -q "." && dirname "{{{{}}}}"' \\; \
184 -exec sh -c 'git -C "$(dirname "{{{{}}}}")" diff --raw --diff-filter=M \
185 | awk -v path="$(dirname "{{{{}}}}")" \
186 "\\$1 ~ /160000\\$/{{{{ print path \\"/\\" \\$6 }}}}"' \\; \
187 | awk '{{{{ if (!seen[$0]++) {{{{ print; fflush() }}}} }}}}' \
188 ;
189 """
191 # Enable discovery
192 elif discover:
193 section_discover = f"""
194 find \
195 -maxdepth '{depth}' \
196 -name '.git' \
197 -not -path '*/.cache/*' \
198 -not -path '*/build/*' \
199 -exec dirname {{{{}}}} \\; \
200 ;
201 """
203 # Prepare separator
204 if presets and discover:
205 section_separator = f'echo \'{SEPARATOR_LONG}\';'
207 # Provide command
208 return f"""
209 {section_options}
210 {section_presets}
211 {section_separator}
212 {section_discover}
213 """
215# Run fzf menu, pylint: disable=too-many-arguments,too-many-positional-arguments
216def run_fzf(
217 configuration: str,
218 presets: bool,
219 differences: bool,
220 discover: bool,
221 depth: int,
222 preview: bool = True,
223) -> str:
225 # Align preview
226 terminal = get_terminal_size()
227 preview_position: str = 'right'
228 if terminal.columns / 2 < terminal.lines:
229 preview_position = 'down'
231 # Align padding
232 padding_width: int = 10
233 if terminal.columns < 100:
234 padding_width = 1
235 elif terminal.columns < 150:
236 padding_width = 5
238 # Configure fzf
239 if 'FZF_DEFAULT_OPTS' not in environ:
240 environ['FZF_DEFAULT_OPTS'] = """
241 --color 'bg:#1b1d1E,bg+:#293739'
242 --color 'border:#808080'
243 --color 'spinner:#e6db74'
244 --color 'hl:#7e8e91,hl+:#f92672'
245 --color 'fg:#f8f8f2,fg+:#f8f8f2'
246 --color 'list-border:#669966,list-label:#99cc99'
247 --color 'info:#a6e22e'
248 --color 'input-border:#996666,input-label:#ffcccc'
249 --color 'label:#808080'
250 --color 'footer:#808080,footer-border:#808080,footer-label:#808080'
251 --color 'marker:#f92672'
252 --color 'pointer:#a6e22e'
253 --color 'prompt:#f92672'
254 --color 'preview-border:#6699cc,preview-label:#99ccff'
255 """
257 # Show fzf
258 return Tools.run_output(
259 [
260 BINARY_FZF,
261 ] + ([
262 '--bind',
263 'focus:transform-preview-label:[ ! -z {} ] && printf " Preview: %s " {}',
264 ] if preview else []) + [
265 '--bind',
266 'enter:accept+abort',
267 '--bind',
268 'start:reload-sync:' + provide_fzf_reload(
269 presets,
270 configuration,
271 depth,
272 discover,
273 differences,
274 ),
275 '--bind',
276 'tab:toggle+down',
277 '--bind',
278 'shift-tab:toggle+up',
279 '--bind',
280 'ctrl-a:toggle-all',
281 '--bind',
282 'alt-a:toggle-all',
283 '--bind',
284 'alt-A:deselect-all',
285 '--border',
286 '--border-label',
287 f' {Tools.NAME} ({Bundle.NAME}) ',
288 '--footer',
289 'Enter: confirm | Ctrl+C: exit | TAB / Ctrl+click: toggle' + linesep +
290 'Ctrl/Alt+A: toggle all | Alt+Shift+A: deselect all',
291 '--footer-label',
292 ' Key bindings ',
293 '--input-label',
294 ' Create panel with selection ',
295 '--layout',
296 'reverse',
297 '--list-label',
298 ' Dashboard list ',
299 '--multi',
300 '--padding',
301 f'1,{padding_width}',
302 ] + ([
303 '--preview',
304 f'{provide_fzf_preview(configuration)}',
305 '--preview-label',
306 ' Preview ',
307 '--preview-window',
308 f'{preview_position}:45%',
309 ] if preview else []) + [
310 '--prompt',
311 '> ',
312 '--style',
313 'full',
314 ],
315 silent=False,
316 stderr=False,
317 )
319# Dashboard panel of Git paths, pylint: disable=duplicate-code,too-many-arguments,too-many-positional-arguments
320def git_dashboard_panel(
321 presets: bool,
322 differences: bool,
323 discovery: bool,
324 add_cwd: bool,
325 depth: int,
326 editor: str,
327 tabs: bool,
328 no_preview: bool,
329) -> int:
331 # Variables
332 configuration: Path
333 selections: List[str]
334 userspace: Path
336 # Validate dependencies
337 if not which(BINARY_FZF):
338 print(' ')
339 print(f'{Colors.YELLOW} {Tools.NAME}:'
340 f'{Colors.RED} Missing dependency \'{BINARY_FZF}\' detected'
341 f'{Colors.RESET}')
342 print(' ')
343 Platform.flush()
344 sleep(3)
345 return -1
347 # Prepare configuration
348 userspace = Platform.userspace(name=Bundle.NAME)
349 userspace.mkdir(parents=True, exist_ok=True)
350 configuration = userspace / CONFIGURATION_PATH
351 if not path.exists(configuration):
352 with open(configuration, 'w', encoding='utf-8') as file:
353 print(environ.get('HOME', ''), file=file)
354 print('', file=file)
355 print(getcwd(), file=file)
357 # Add current working path
358 if add_cwd:
359 cwd: str = getcwd()
360 with open(configuration, 'a', encoding='utf-8') as file:
361 print('', file=file)
362 print(cwd, file=file)
363 print(' ')
364 print(f'{Colors.YELLOW} {Tools.NAME}:'
365 f'{Colors.GREEN} Added \''
366 f'{Colors.CYAN}{cwd}'
367 f'{Colors.GREEN}\' to dashboard configuration'
368 f'{Colors.RESET}')
369 print(' ')
370 Platform.flush()
371 return 0
373 # Run entrypoint
374 while True:
376 # Show menu
377 selections = run_fzf(
378 configuration=str(configuration),
379 presets=presets,
380 differences=differences,
381 discover=discovery,
382 depth=depth,
383 preview=not tabs and not no_preview,
384 ).strip().splitlines()
386 # Interrupt menu
387 if not selections or LABEL_EXIT in selections:
388 break
390 # Reload dashboard
391 if LABEL_RELOAD in selections:
392 continue
394 # Edit dashboard
395 if LABEL_CONFIGURE in selections:
396 Tools.run_command([
397 editor,
398 str(configuration),
399 ])
400 continue
402 # Ignore separators
403 selections = [
404 selection for selection in selections
405 if selection not in [SEPARATOR_SHORT, SEPARATOR_LONG]
406 ]
408 # Iterate over selections
409 for selection in selections:
411 # Resolve path
412 selection = str(Path(selection).resolve())
414 # Open path
415 open_path(selection, tabs)
417 # Delay
418 if len(selections) > 1:
419 sleep(0.1)
421 # Single action usage
422 if differences:
423 break
425 # Result
426 return 0
428# Main, pylint: disable=duplicate-code,too-many-statements
429def main() -> None:
431 # Variables
432 differences: bool
433 discovery: bool
434 group: _ArgumentGroup
435 presets: bool
436 result: int
437 subgroup: _MutuallyExclusiveGroup
439 # Configure tool
440 Tools.NAME = 'git dashboard-panel'
441 Tools.DESCRIPTION = 'Dashboard panel of Git paths with interactive selection'
443 # Arguments creation
444 parser: ArgumentParser = ArgumentParser(
445 prog=Tools.NAME,
446 description=f'{Tools.NAME}: {Tools.DESCRIPTION} ({Bundle.NAME})',
447 add_help=False,
448 formatter_class=lambda prog: RawTextHelpFormatter(
449 prog,
450 max_help_position=HELP_POSITION,
451 width=min(
452 120,
453 get_terminal_size().columns - 2,
454 ),
455 ),
456 )
458 # Arguments tool definitions
459 group = parser.add_argument_group('tool arguments')
460 group.add_argument(
461 '-h',
462 '--help',
463 dest='help',
464 action='store_true',
465 help='Show this help message',
466 )
467 group.add_argument(
468 '-L',
469 '--depth',
470 dest='depth',
471 type=int,
472 default=10,
473 metavar='LEVEL',
474 help='Maximum depth for Git paths discovery (default: %(default)s)',
475 )
476 group.add_argument(
477 '--editor',
478 dest='editor',
479 default=environ.get('EDITOR', 'nano'),
480 help='Editor binary to use for configuration editing',
481 )
482 group.add_argument(
483 '-t',
484 '--tabs',
485 dest='tabs',
486 action='store_true',
487 help='Open in split tabs instead of windows',
488 )
489 group.add_argument(
490 '-P',
491 '--no-preview',
492 dest='no_preview',
493 action='store_true',
494 help='Disable dashboard preview section',
495 )
497 # Arguments modes definitions
498 group = parser.add_argument_group('modes arguments')
499 subgroup = group.add_mutually_exclusive_group()
500 subgroup.add_argument(
501 '--current',
502 dest='current',
503 action='store_true',
504 help='Show only current Git paths discovery',
505 )
506 subgroup.add_argument(
507 '--differences',
508 dest='differences',
509 action='store_true',
510 help='Show only Git paths having uncommitted differences',
511 )
512 subgroup.add_argument(
513 '--presets',
514 dest='presets',
515 action='store_true',
516 help='Show only configuration paths presets',
517 )
518 subgroup.add_argument(
519 '--add-cwd',
520 dest='add_cwd',
521 action='store_true',
522 help='Add current working path to dashboard configuration',
523 )
525 # Arguments autocompletion
526 autocomplete(parser)
528 # Arguments parser
529 options: Namespace = parser.parse_args()
531 # Help informations
532 if options.help:
533 print(' ')
534 parser.print_help()
535 print(' ')
536 Platform.flush()
537 sys_exit(0)
539 # Parse modes
540 if options.current:
541 discovery = True
542 differences = False
543 presets = False
544 elif options.differences:
545 discovery = True
546 differences = True
547 presets = False
548 elif options.presets:
549 discovery = False
550 differences = False
551 presets = True
552 elif options.add_cwd:
553 discovery = False
554 differences = False
555 presets = False
556 else:
557 discovery = True
558 differences = False
559 presets = True
561 # Instantiate settings
562 settings: Settings = Settings(name=Bundle.NAME)
564 # Prepare colors
565 Colors.prepare()
567 # Instantiate updates
568 updates: Updates = Updates(
569 name=Bundle.PACKAGE,
570 settings=settings,
571 )
573 # Run tool
574 result = git_dashboard_panel(
575 presets=presets,
576 differences=differences,
577 discovery=discovery,
578 add_cwd=options.add_cwd,
579 depth=options.depth,
580 editor=options.editor,
581 tabs=options.tabs,
582 no_preview=options.no_preview,
583 )
585 # Check for daily updates
586 if updates.enabled and updates.daily:
587 updates.check()
589 # Result
590 sys_exit(0 if result >= 0 else result)
592# Entrypoint
593if __name__ == '__main__': # pragma: no cover
594 main()