Coverage for src/cli/entrypoint.py: 11.24%
178 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-07 23:50 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-07 23:50 +0000
1#!/usr/bin/env python3
3# Standard libraries
4from argparse import Namespace
5from enum import Enum
6from typing import Dict, List, Optional
7import urllib.parse
9# Modules libraries
10from gitlab.config import ConfigError, GitlabConfigParser
11from gitlab.exceptions import (
12 GitlabGetError, )
13from gitlab.v4.objects import (
14 Project as GitLabProject,
15 ProjectMilestone,
16)
18# Components
19from ..features.gitlab import GitLabFeature
20from ..types.milestones import MilestoneDescription
21from ..types.statistics import AssigneeStatistics, MilestoneStatistics, TimesStatistics
22from ..prints.colors import Colors
23from ..system.platform import Platform
24from ..types.environments import Environments
25from ..types.gitlab import MilestoneState
27# Entrypoint class, pylint: disable=too-few-public-methods
28class Entrypoint:
30 # Enumerations
31 Result = Enum('Result', [
32 'SUCCESS',
33 'FINALIZE',
34 'ERROR',
35 'CRITICAL',
36 ])
38 # CLI, pylint: disable=too-many-branches
39 @staticmethod
40 def cli(
41 options: Namespace,
42 environments: Environments,
43 ) -> Result:
45 # Variables
46 project: Optional[GitLabProject] = None
47 result: Entrypoint.Result
49 # Header
50 print(' ')
52 # Parse URL variables
53 gitlab_splits: urllib.parse.SplitResult = urllib.parse.urlsplit(options.url_path)
54 gitlab_id: str = f'{gitlab_splits.netloc}'
55 gitlab_url: str = f'{gitlab_splits.scheme}://{gitlab_splits.netloc}'
56 gitlab_path: str = gitlab_splits.path.lstrip('/')
58 # Prepare credentials
59 private_token: str = environments.value('gitlab_token')
60 job_token: str = environments.value('ci_job_token')
61 ssl_verify: bool | str = True
63 # Parse configuration files
64 try:
65 config: GitlabConfigParser
66 if not private_token:
67 config = GitlabConfigParser(gitlab_id, options.configs)
68 private_token = str(config.private_token)
69 if ssl_verify and (not config.ssl_verify
70 or isinstance(config.ssl_verify, str)):
71 ssl_verify = config.ssl_verify
72 except ConfigError as e:
73 print(str(e))
75 # GitLab client
76 gitlab = GitLabFeature(
77 url=gitlab_url,
78 private_token=private_token,
79 job_token=job_token,
80 ssl_verify=ssl_verify,
81 )
82 print(f'{Colors.BOLD} - GitLab host: '
83 f'{Colors.GREEN}{gitlab.url}'
84 f'{Colors.RESET}')
85 Platform.flush()
87 # GitLab path
88 project = gitlab.project(gitlab_path)
89 print(f'{Colors.BOLD} - GitLab project: '
90 f'{Colors.GREEN}{project.path_with_namespace}'
91 f'{Colors.CYAN} ({project.description})'
92 f'{Colors.RESET}')
93 print(' ')
94 Platform.flush()
96 # Handle single project
97 result = Entrypoint.project(
98 options,
99 gitlab,
100 project.path_with_namespace,
101 )
102 if result != Entrypoint.Result.SUCCESS:
103 return result
105 # Result
106 return Entrypoint.Result.SUCCESS
108 # Project, pylint: disable=too-many-locals,too-many-statements
109 @staticmethod
110 def project(
111 options: Namespace,
112 gitlab: GitLabFeature,
113 criteria: str,
114 ) -> Result:
116 # Variables
117 milestone: MilestoneStatistics
118 milestone_data: ProjectMilestone
119 milestone_description: str
120 milestones_statistics: Dict[str, MilestoneStatistics] = {}
122 # Acquire project
123 project = gitlab.project(criteria)
125 # Show project details
126 print(f'{Colors.BOLD} - GitLab project: '
127 f'{Colors.YELLOW_LIGHT}{project.path_with_namespace} '
128 f'{Colors.CYAN}({project.description})'
129 f'{Colors.RESET}')
130 Platform.flush()
132 # Create milestone
133 if options.create_milestone:
135 # Validate issues feature
136 if not project.issues_enabled:
137 raise RuntimeError('GitLab issues feature not enabled')
139 # Create new milestone
140 project.milestones.create({
141 'title': options.milestone,
142 })
144 # Get milestone
145 elif options.get_milestone:
147 # Validate issues feature
148 if not project.issues_enabled:
149 raise RuntimeError('GitLab issues feature not enabled')
151 # Find milestone
152 try:
153 milestone_data = next(
154 milestone_data
155 for milestone_data in project.milestones.list(get_all=True)
156 if milestone_data.title == options.milestone
157 and isinstance(milestone_data, ProjectMilestone))
158 except StopIteration as exc:
159 raise GitlabGetError(
160 f'Could not find milestone \'{options.milestone}\' in project \'{criteria}\''
161 ) from exc
163 # Show milestone
164 print(' ')
165 print(f'{Colors.BOLD} - Milestone: '
166 f'{Colors.CYAN}{milestone_data.title}'
167 f'{Colors.RESET}')
168 print(f'{Colors.BOLD} - Description: '
169 f'{Colors.GREEN}{milestone_data.description or "/"}'
170 f'{Colors.RESET}')
171 print(f'{Colors.BOLD} - State: '
172 f'{Colors.GREEN}{milestone_data.state or "?"}'
173 f'{Colors.RESET}')
174 print(f'{Colors.BOLD} - Start date: '
175 f'{Colors.GREEN}{milestone_data.start_date or "/"}'
176 f'{Colors.RESET}')
177 print(f'{Colors.BOLD} - Due date: '
178 f'{Colors.GREEN}{milestone_data.due_date or "/"}'
179 f'{Colors.RESET}')
180 Platform.flush()
182 # Set milestone settings
183 if options.set_milestone_description \
184 or options.set_milestone_state \
185 or options.set_milestone_start_date \
186 or options.set_milestone_due_date:
188 # Find milestone
189 try:
190 milestone_data = next(
191 milestone_data
192 for milestone_data in project.milestones.list(get_all=True)
193 if milestone_data.title == options.milestone
194 and isinstance(milestone_data, ProjectMilestone))
195 except StopIteration as exc:
196 raise GitlabGetError(
197 f'Could not find milestone \'{options.milestone}\' in project \'{criteria}\''
198 ) from exc
200 # Show milestone
201 print(' ')
202 print(f'{Colors.BOLD} - Milestone: '
203 f'{Colors.CYAN}{milestone_data.title or "/"}'
204 f'{Colors.RESET}')
206 # Set milestone description
207 if options.set_milestone_description is not None:
208 milestone_data.description = options.set_milestone_description
209 print(f'{Colors.BOLD} - Set milestone description: '
210 f'{Colors.CYAN}{milestone_data.description or "/"}'
211 f'{Colors.RESET}')
212 Platform.flush()
214 # Set milestone state
215 if options.set_milestone_state:
216 if options.set_milestone_state not in MilestoneState.names():
217 raise SyntaxError(f'Unknown state: {options.set_milestone_state}'
218 f' ({",".join(MilestoneState.names())})')
219 milestone_data.state_event = options.set_milestone_state
220 print(f'{Colors.BOLD} - Set milestone state: '
221 f'{Colors.CYAN}{milestone_data.state_event}'
222 f'{Colors.RESET}')
223 Platform.flush()
225 # Set milestone start date
226 if options.set_milestone_start_date is not None:
227 milestone_data.start_date = options.set_milestone_start_date
228 print(f'{Colors.BOLD} - Set milestone start date: '
229 f'{Colors.CYAN}{milestone_data.start_date or "/"}'
230 f'{Colors.RESET}')
231 Platform.flush()
233 # Set milestone due date
234 if options.set_milestone_due_date is not None:
235 milestone_data.due_date = options.set_milestone_due_date
236 print(f'{Colors.BOLD} - Set milestone due date: '
237 f'{Colors.CYAN}{milestone_data.due_date or "/"}'
238 f'{Colors.RESET}')
239 Platform.flush()
241 # Save milestone
242 milestone_data.save()
244 # Detect milestones
245 if options.milestones_statistics:
247 # Validate issues feature
248 if not project.issues_enabled:
249 raise RuntimeError('GitLab issues feature not enabled')
251 # Issues without milestone
252 if not options.milestone or options.milestone == 'None':
253 milestones_statistics[''] = MilestoneStatistics('Without milestone', )
254 milestones_statistics[''].assignees[''] = AssigneeStatistics(
255 'Without assignee', )
257 # Iterate through milestones
258 for milestone_obj in sorted(
259 project.milestones.list(
260 get_all=True,
261 state='active' if options.exclude_closed_milestones else None,
262 ), key=lambda milestone: milestone.due_date
263 if milestone.due_date else MilestoneDescription.DUE_DATE_UNDEFINED,
264 reverse=False):
266 # Filter specific milestone
267 if options.milestone and options.milestone != 'None' and options.milestone not in [
268 str(milestone_obj.id), milestone_obj.title
269 ]:
270 continue
272 # Issues with milestone
273 milestones_statistics[milestone_obj.id] = MilestoneStatistics(
274 milestone_obj.title, )
275 milestones_statistics[
276 milestone_obj.id].assignees[''] = AssigneeStatistics(
277 'Without assignee', )
279 # Iterate through issues
280 for issue in project.issues.list(
281 get_all=True,
282 order_by='created_at',
283 sort='asc',
284 state='opened' if options.exclude_closed_issues else None,
285 ):
287 # Validate milestone ID
288 milestone_id = issue.milestone[
289 'id'] if issue.milestone and 'id' in issue.milestone else ''
290 if not milestone_id:
291 if issue.issue_type == 'task':
292 print(f'{Colors.BOLD} - GitLab issue: '
293 f'{Colors.YELLOW_LIGHT}Task #{issue.iid}'
294 f'{Colors.GREY} ({issue.title})'
295 f'{Colors.YELLOW_LIGHT} is missing a known milestone...'
296 f'{Colors.RESET}')
297 print(f'{Colors.BOLD} - URL: '
298 f'{Colors.CYAN}{issue.web_url}'
299 f'{Colors.RESET}')
300 elif not options.ignore_issues_without_milestone:
301 print(f'{Colors.BOLD} - GitLab issue: '
302 f'{Colors.RED}Issue #{issue.iid}'
303 f'{Colors.GREY} ({issue.title})'
304 f'{Colors.RED} is missing a known milestone...'
305 f'{Colors.RESET}')
306 print(f'{Colors.BOLD} - URL: '
307 f'{Colors.CYAN}{issue.web_url}'
308 f'{Colors.RESET}')
309 return Entrypoint.Result.ERROR
310 continue
311 if milestone_id not in milestones_statistics:
312 continue
314 # Get milestone statistics
315 milestone = milestones_statistics[milestone_id]
317 # Parse issue timings
318 defaulted: bool = 'time_estimate' not in issue.time_stats(
319 ) or issue.time_stats()['time_estimate'] == 0
320 if not defaulted:
321 if issue.state != 'closed':
322 time_estimate = issue.time_stats()['time_estimate']
323 time_spent = issue.time_stats()['total_time_spent']
324 else:
325 time_estimate = issue.time_stats()['time_estimate']
326 time_spent = time_estimate
327 else:
328 time_estimate = int(options.default_estimate) * 60 * 60
329 if issue.state != 'closed':
330 time_spent = 0
331 else:
332 time_spent = time_estimate
334 # Handle milestone statistics
335 milestone.issues_count += 1
336 if not milestone.times.defaulted and defaulted:
337 milestone.times.defaulted = True
338 milestone.times.estimates += time_estimate
339 milestone.times.spent += time_spent
341 # Prepare issue assignee
342 assignee_id = issue.assignee[
343 'id'] if issue.assignee and 'id' in issue.assignee else ''
344 if assignee_id not in milestone.assignees:
345 milestone.assignees[assignee_id] = AssigneeStatistics(
346 issue.assignee['name'], )
348 # Handle assignee statistics
349 milestone.assignees[assignee_id].issues_count += 1
350 if not milestone.assignees[assignee_id].times.defaulted and defaulted:
351 milestone.assignees[assignee_id].times.defaulted = True
352 milestone.assignees[assignee_id].times.estimates += time_estimate
353 milestone.assignees[assignee_id].times.spent += time_spent
355 # Dump issue object
356 if options.dump:
357 print(' ')
358 print(issue.to_json())
360 # Create milestones statistics
361 for milestone_id, milestone in milestones_statistics.items():
362 if not milestone.issues_count:
363 continue
365 # Create milestone section
366 outputs: List[str] = []
367 outputs += ['']
368 outputs += [f'# Milestone statistics - {milestone.title}']
369 outputs += ['']
371 # Create milestone table
372 outputs += [
373 '| Assignees | Issues | Estimated | Spent | Remaining | Progress |'
374 ]
375 outputs += [
376 '|-----------|--------|-----------|-------|-----------|----------|'
377 ]
379 # Inject milestone table per assignee
380 for _, assignee in milestone.assignees.items():
381 if not assignee.issues_count:
382 continue
383 times = assignee.times
384 outputs += [
385 f'| **{assignee.name}** '
386 f'| {assignee.issues_count} '
387 f'| {TimesStatistics.human(times.estimates, times.defaulted)} '
388 f'| {TimesStatistics.human(times.spent, times.defaulted)} '
389 f'| {TimesStatistics.human(times.remaining, times.defaulted)} '
390 f'| {times.progress()} '
391 f'|'
392 ]
394 # Inject milestone table total
395 times = milestone.times
396 outputs += [
397 '| _**Total**_ '
398 f'| _{milestone.issues_count}_ '
399 f'| _{TimesStatistics.human(times.estimates, times.defaulted)}_ '
400 f'| _{TimesStatistics.human(times.spent, times.defaulted)}_ '
401 f'| {TimesStatistics.human(times.remaining, times.defaulted)} '
402 f'| _{times.progress()}_ '
403 '|'
404 ]
406 # Export to terminal
407 for line in outputs:
408 print(f' {line}')
410 # Export to milestone
411 if milestone_id:
412 milestone_obj = project.milestones.get(milestone_id)
413 milestone_description = MilestoneDescription.inject_statistics(
414 description=milestone_obj.description,
415 statistics='\n'.join(outputs),
416 )
417 if MilestoneDescription.updated_statistics(milestone_obj.description,
418 milestone_description):
419 milestone_obj.description = milestone_description
420 milestone_obj.save()
422 # Dump project object
423 if options.dump:
424 print(' ')
425 print(project.to_json())
427 # Footer
428 print(' ')
429 Platform.flush()
431 # Result
432 return Entrypoint.Result.SUCCESS