Coverage for src/tools/tools.py: 24.17%
120 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# Standard libraries
2from os import environ, walk
3from pathlib import Path
4from subprocess import run, CalledProcessError, DEVNULL, PIPE
5from typing import Dict, List, Optional
7# Modules libraries
8from questionary import text as questionary_text
10# Components
11from ..prints.colors import Colors
13# Tools class
14class Tools:
16 # Members
17 DESCRIPTION: str = ''
18 NAME: str = ''
20 # Run command
21 @staticmethod
22 def run_command(
23 command: list[str],
24 stdout: bool = True,
25 stderr: bool = True,
26 env: Optional[Dict[str, str]] = None,
27 cwd: Optional[str] = None,
28 ) -> int:
29 return run(
30 command,
31 stdout=None if stdout else DEVNULL,
32 stderr=None if stderr else DEVNULL,
33 text=True,
34 check=False,
35 env={
36 **environ,
37 **env
38 } if env else None,
39 cwd=cwd,
40 ).returncode
42 # Run with output
43 @staticmethod
44 def run_output(
45 command: list[str],
46 silent: bool = True,
47 stderr: bool = True,
48 ) -> str:
49 try:
50 result = run(
51 command,
52 text=True,
53 check=True,
54 stdout=PIPE,
55 stderr=PIPE if stderr else DEVNULL if silent else None,
56 )
57 return str(result.stdout.strip())
58 except CalledProcessError as error:
59 if error.stderr:
60 if not silent:
61 print(error.stderr.strip())
62 if stderr:
63 return str(error.stderr.strip())
64 return ''
66 # Get git branches
67 @staticmethod
68 def git_branches(remote: str) -> List[str]:
70 # Variables
71 branches: List[str]
73 # Acquire branches
74 branches = sorted({
75 line.split(f'{remote}/')[-1]
76 for line in Tools.run_output(
77 [
78 'git',
79 'branch',
80 '-ar',
81 ],
82 stderr=False,
83 ).splitlines() if line.lstrip().startswith(remote) and '->' not in line
84 })
86 # Result
87 return branches if branches else []
89 # Get .git directory
90 @staticmethod
91 def git_dir() -> str:
92 return Tools.run_output(
93 [
94 'git',
95 'rev-parse',
96 '--git-dir',
97 ],
98 stderr=False,
99 )
101 # Fetch remote branch
102 @staticmethod
103 def git_fetch(remote: str, branch: str) -> bool:
104 return Tools.run_command([
105 'git',
106 'fetch',
107 remote,
108 branch,
109 ]) == 0
111 # Get git hooks
112 @staticmethod
113 def git_hooks() -> List[str]:
115 # Variables
116 git_dir: str
117 hooks: List[str] = []
119 # Access .git
120 git_dir = Tools.git_dir()
121 if not git_dir:
122 return []
124 # Detect hooks
125 hooks_dir = Path(git_dir) / 'hooks'
126 for hooks_item in hooks_dir.iterdir():
127 if hooks_item.is_file() and not hooks_item.name.endswith('.sample'):
128 hooks.append(hooks_item.name)
130 # Result
131 return hooks
133 # Get git remotes
134 @staticmethod
135 def git_remotes() -> List[str]:
137 # Variables
138 remotes: List[str]
140 # Acquire remotes
141 remotes = Tools.run_output(
142 [
143 'git',
144 'remote',
145 ],
146 stderr=False,
147 ).splitlines()
149 # Result
150 return remotes if remotes else []
152 # Get git repositories
153 @staticmethod
154 def git_repositories(
155 root_path: str = '.',
156 submodules: bool = True,
157 ) -> List[str]:
159 # Variables
160 repositories: List[str] = []
162 # Walk through path
163 base_path = Path(root_path)
164 for child_path, child_dirs, _ in walk(base_path):
166 # Detect git repository
167 if '.git' in child_dirs:
169 # Store repositories
170 repositories.append(str(Path(child_path)))
171 child_dirs.clear()
173 # Handle submodules
174 if submodules:
175 submodule_paths = Tools.run_output(
176 [
177 'git',
178 'submodule',
179 'foreach',
180 '--quiet',
181 'echo "${sm_path}"',
182 ],
183 stderr=False,
184 ).splitlines()
185 repositories.extend(submodule_paths)
187 # Base repository
188 if child_path == root_path:
189 break
191 # Result
192 return repositories
194 # Select remote
195 @staticmethod
196 def select_remote() -> str:
198 # Acquire remotes
199 remotes = Tools.git_remotes()
200 if not remotes:
201 return ''
203 # Detect single remote
204 if len(remotes) == 1:
205 return remotes[0]
207 # Selector header
208 print(' ')
209 print(f'{Colors.GREEN} === {Tools.NAME} - Remote selection ==='
210 f'{Colors.RESET}')
211 print(' ')
213 # Selector items
214 for idx, remote in enumerate(remotes, start=1):
215 remote_url = Tools.run_output([
216 'git',
217 'config',
218 '--get',
219 f'remote.{remote}.url',
220 ])
221 print(
222 f'{Colors.YELLOW} [{idx}] {Colors.BOLD}{remote} - {Colors.YELLOW_THIN}{remote_url}'
223 f'{Colors.RESET}')
225 # Selector input
226 print(' ')
227 try:
228 print(
229 f'{Colors.YELLOW} {Tools.NAME}:'
230 f'{Colors.BOLD} Choose a remote'
231 f'{Colors.GREEN} [1-{len(remotes)}]'
232 f' {Colors.YELLOW}:'
233 f'{Colors.RESET}',
234 end='',
235 )
236 choice: Optional[str] = questionary_text(
237 message='',
238 default='',
239 validate=None,
240 qmark='',
241 style=None,
242 multiline=False,
243 instruction=None,
244 lexer=None,
245 ).ask()
246 if choice and 1 <= int(choice) <= len(remotes):
247 return remotes[int(choice) - 1]
248 raise ValueError
250 # Selector interruption
251 except KeyboardInterrupt:
252 print(' ')
253 return ''
255 # Selector fallback
256 except (IndexError, ValueError):
257 return ''
259 # Select branch
260 @staticmethod
261 def select_branch(remote: str) -> str:
263 # Validate input
264 if not remote:
265 return ''
267 # Acquire branches
268 branches = Tools.git_branches(remote)
270 # Selector header
271 print(' ')
272 print(f'{Colors.GREEN} === {Tools.NAME} - Branch selection ==='
273 f'{Colors.RESET}')
274 print(' ')
276 # Selector items
277 print(f'{Colors.YELLOW} [0] {Colors.BOLD}Manual branch input'
278 f'{Colors.RESET}')
279 if branches:
280 print(' ')
281 for idx, branch in enumerate(branches, start=1):
282 print(
283 f'{Colors.YELLOW} [{idx}] {Colors.BOLD}{branch} - {Colors.YELLOW_THIN}{remote}'
284 f'{Colors.RESET}')
286 # Selector input
287 print(' ')
288 try:
289 print(
290 f'{Colors.YELLOW} {Tools.NAME}:'
291 f'{Colors.BOLD} Select branch'
292 f'{Colors.GREEN} [0-{len(branches)}]'
293 f' {Colors.RESET}:',
294 end='',
295 )
297 # User selection
298 if len(branches) > 0:
299 choice: Optional[str] = questionary_text(
300 message='',
301 default='',
302 validate=None,
303 qmark='',
304 style=None,
305 multiline=False,
306 instruction=None,
307 lexer=None,
308 ).ask()
310 # Empty selection
311 else:
312 choice = '0'
313 print(f'{Colors.YELLOW_LIGHT} 0'
314 f'{Colors.CYAN} (No selection available)'
315 f'{Colors.RESET}')
317 # Manual branch input
318 if choice and int(choice) == 0:
319 print(
320 f'{Colors.YELLOW} {Tools.NAME}:'
321 f'{Colors.BOLD} Remote branch input'
322 f' {Colors.RESET}:',
323 end='',
324 )
325 branch = questionary_text(
326 message='',
327 default='',
328 validate=None,
329 qmark='',
330 style=None,
331 multiline=False,
332 instruction=None,
333 lexer=None,
334 ).ask()
335 return branch.strip() if branch else ''
337 # Branch selection
338 if choice and 1 <= int(choice) <= len(branches):
339 return branches[int(choice) - 1]
341 # Unknown selection
342 raise ValueError
344 # Selector interruption
345 except KeyboardInterrupt:
346 print(' ')
347 return ''
349 # Selector fallback
350 except (IndexError, ValueError):
351 return ''