healthycode 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,814 @@
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) Bitergia
4
+ # Copyright (C) AboutCode
5
+ #
6
+ # This program is free software; you can redistribute it and/or modify
7
+ # it under the terms of the GNU General Public License as published by
8
+ # the Free Software Foundation; either version 3 of the License, or
9
+ # (at your option) any later version.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
+ #
19
+
20
+ from __future__ import annotations
21
+
22
+ import datetime
23
+ import logging
24
+ import numpy
25
+ import re
26
+ import typing
27
+
28
+ from collections import Counter
29
+
30
+ from math import sqrt
31
+
32
+ from opensearchpy import OpenSearch, Search, Q
33
+
34
+ from grimoirelab_toolkit.datetime import (
35
+ str_to_datetime,
36
+ datetime_utcnow,
37
+ datetime_to_utc,
38
+ InvalidDateError,
39
+ )
40
+
41
+ logging.getLogger("opensearch").setLevel(logging.WARNING)
42
+
43
+
44
+ if typing.TYPE_CHECKING:
45
+ from typing import Any
46
+
47
+
48
+ GIT_EVENT_COMMIT = "org.grimoirelab.events.git.commit"
49
+ GIT_EVENT_ACTION_ADDED = "org.grimoirelab.events.git.file.added"
50
+ GIT_EVENT_ACTION_DELETED = "org.grimoirelab.events.git.file.deleted"
51
+ GIT_EVENT_ACTION_REPLACED = "org.grimoirelab.events.git.file.replaced"
52
+ GIT_EVENT_ACTION_COPIED = "org.grimoirelab.events.git.file.copied"
53
+ GIT_EVENT_FILE_ACTIONS = [
54
+ GIT_EVENT_ACTION_ADDED,
55
+ GIT_EVENT_ACTION_DELETED,
56
+ GIT_EVENT_ACTION_REPLACED,
57
+ GIT_EVENT_ACTION_COPIED,
58
+ ]
59
+
60
+ AUTHOR_FIELD = "Author"
61
+ FILE_TYPE_CODE = (
62
+ r"\.bazel$|\.bazelrc$|\.bzl$|\.c$|\.cc$|\.cp$|\.cpp$|\.cs$\|\.cxx$|\.c\+\+$|"
63
+ r"\.go$|\.h$|\.hpp$|\.js$|\.mjs$|\.java$|\.pl$|\.py$|\.rs$|\.sh$|\.tf$|\.ts$"
64
+ )
65
+ FILE_TYPE_BINARY = (
66
+ r"\.7z$|\.a$|\.abb$|\.apk$|\.app$|\.appx$|\.arc$|\.bin$|\.bz2$|\.class$|\.deb$|"
67
+ r"\.dll$|\.dmg$|\.exe$|\.gz$|\.ipa$|\.iso$|\.jar$|\.lib$|\.msi$|\.o$|\.obj$|\.rar$|"
68
+ r"\.rpm$|\.so$|\.tar$|\.xar$|\.xz$|\.zip$|\.zst$|\.Z$"
69
+ )
70
+ LICENSE_FILE_REGEX = r"LICENSE|LICENSE\.md|LICENSE\.txt|COPYING"
71
+ ADOPTERS_FILE_REGEX = r"ADOPTERS|ADOPTERS\.md|ADOPTERS\.txt"
72
+ COMPILED_LICENSE_FILE_REGEX = re.compile(LICENSE_FILE_REGEX)
73
+ COMPILED_ADOPTERS_FILE_REGEX = re.compile(ADOPTERS_FILE_REGEX)
74
+
75
+
76
+ class GitEventsAnalyzer:
77
+ def __init__(
78
+ self,
79
+ from_date: datetime.datetime | None = None,
80
+ to_date: datetime.datetime | None = None,
81
+ code_file_pattern: str | None = None,
82
+ binary_file_pattern: str | None = None,
83
+ pony_threshold: float = 0.5,
84
+ elephant_threshold: float = 0.5,
85
+ dev_categories_thresholds: tuple[float, float] = (0.8, 0.95),
86
+ ):
87
+ # Define the default dates if not provided
88
+ if from_date:
89
+ self.from_date = datetime_to_utc(from_date)
90
+ else:
91
+ self.from_date = datetime_utcnow() - datetime.timedelta(days=365)
92
+ if to_date:
93
+ self.to_date = datetime_to_utc(to_date)
94
+ else:
95
+ self.to_date = datetime_utcnow()
96
+
97
+ self.total_commits: int = 0
98
+ self.recent_commits: int = 0
99
+ self.contributors: Counter = Counter()
100
+ self.contributors_growth: dict[str, set] = {"first_half": set(), "second_half": set()}
101
+ self.returning_contributors: dict[str, set] = {"first_period": set(), "second_period": set()}
102
+ self.organizations: Counter = Counter()
103
+ self.recent_organizations: set = set()
104
+ self.recent_contributors: set = set()
105
+ self.file_types: dict = {"code": 0, "binary": 0, "other": 0}
106
+ self.added_lines: int = 0
107
+ self.removed_lines: int = 0
108
+ self.messages_sizes: list = []
109
+ self.re_code_pattern = re.compile(code_file_pattern or FILE_TYPE_CODE)
110
+ self.re_binary_pattern = re.compile(binary_file_pattern or FILE_TYPE_BINARY)
111
+ self.pony_threshold = pony_threshold
112
+ self.elephant_threshold = elephant_threshold
113
+ self.dev_categories_thresholds = dev_categories_thresholds
114
+ self.first_commit: str | None = None
115
+ self.last_commit: str | None = None
116
+ self.first_commit_date: datetime.datetime | None = None
117
+ self.last_commit_date: datetime.datetime | None = None
118
+ self.active_branches: set = set()
119
+ self._half_period = self.from_date + (self.to_date - self.from_date) / 2
120
+ self.files_found: dict[str, int] = {"license": 0, "adopters": 0}
121
+ self.commits_per_month: Counter = Counter()
122
+ self._initialize_months()
123
+
124
+ def _initialize_months(self):
125
+ """Initialize commits_per_month with all months in the date range, starting at 0.
126
+
127
+ We need this for the calculation of the coefficient of variability
128
+ """
129
+ from_month = self.from_date.replace(day=1)
130
+ to_month = self.to_date.replace(day=1)
131
+
132
+ while from_month <= to_month:
133
+ month_key = from_month.strftime("%Y-%m")
134
+ self.commits_per_month[month_key] = 0
135
+ # Move to next month
136
+ if from_month.month == 12:
137
+ from_month = from_month.replace(year=from_month.year + 1, month=1)
138
+ else:
139
+ from_month = from_month.replace(month=from_month.month + 1)
140
+
141
+ def process_events(self, events: iter(dict[str, Any])):
142
+ for event in events:
143
+ if event["type"] == GIT_EVENT_COMMIT:
144
+ event_data = event.get("data")
145
+
146
+ self._update_commit_count(event_data)
147
+ self._update_branches(event_data)
148
+ self._update_contributors(event_data)
149
+ self._update_organizations(event_data)
150
+ self._update_file_metrics(event_data)
151
+ self._update_message_size_metrics(event_data)
152
+ self._update_first_and_last_commit(event_data)
153
+ elif event["type"] in GIT_EVENT_FILE_ACTIONS:
154
+ self._check_files_found(event)
155
+
156
+ def get_commit_count(self):
157
+ return self.total_commits
158
+
159
+ def get_contributor_count(self):
160
+ return len(self.contributors)
161
+
162
+ def get_organization_count(self):
163
+ return len(self.organizations)
164
+
165
+ def get_pony_factor(self):
166
+ """Number of individuals producing up to 50% of the total number of code contributions"""
167
+
168
+ partial_contributions = 0
169
+ pony_factor = 0
170
+
171
+ if len(self.contributors) == 0:
172
+ return 0
173
+
174
+ for _, contributions in self.contributors.most_common():
175
+ partial_contributions += contributions
176
+ pony_factor += 1
177
+ if partial_contributions / self.total_commits > self.pony_threshold:
178
+ break
179
+
180
+ return pony_factor
181
+
182
+ def get_elephant_factor(self):
183
+ """Number of organizations producing up to 50% of the total number of code contributions"""
184
+
185
+ partial_contributions = 0
186
+ elephant_factor = 0
187
+
188
+ if len(self.organizations) == 0:
189
+ return 0
190
+
191
+ for _, contributions in self.organizations.most_common():
192
+ partial_contributions += contributions
193
+ elephant_factor += 1
194
+ if partial_contributions / self.total_commits > self.elephant_threshold:
195
+ break
196
+
197
+ return elephant_factor
198
+
199
+ def get_file_type_metrics(self):
200
+ """Get the file type metrics"""
201
+
202
+ return self.file_types
203
+
204
+ def get_commit_size_metrics(self):
205
+ """Get the commit size metrics"""
206
+
207
+ metrics = {
208
+ "added_lines": self.added_lines,
209
+ "removed_lines": self.removed_lines,
210
+ }
211
+ return metrics
212
+
213
+ def get_message_size_metrics(self):
214
+ """Get the message size metrics"""
215
+
216
+ total = sum(self.messages_sizes)
217
+ number = len(self.messages_sizes)
218
+ mean = 0
219
+ median = 0
220
+ if number > 0:
221
+ mean = total / number
222
+ median = sorted(self.messages_sizes)[number // 2]
223
+
224
+ metrics = {
225
+ "total": total,
226
+ "mean": mean,
227
+ "median": median,
228
+ }
229
+ return metrics
230
+
231
+ def get_commit_frequency_metrics(self, days_interval: int):
232
+ """
233
+ Get the average (mean) number of commits per week, month and
234
+ year if the days of interval is greater than the metrics interval.
235
+
236
+ :param days_interval: Interval of days to calculate the mean
237
+ """
238
+ metrics = {"week": None, "month": None, "year": None}
239
+
240
+ if days_interval >= 7:
241
+ metrics["week"] = self.total_commits / (days_interval / 7)
242
+
243
+ if days_interval >= 30:
244
+ metrics["month"] = self.total_commits / (days_interval / 30)
245
+
246
+ if days_interval >= 365:
247
+ metrics["year"] = self.total_commits / (days_interval / 365)
248
+
249
+ return metrics
250
+
251
+ def get_commit_coefficient_of_variation(self):
252
+ """
253
+ Get the coefficient of variation (mean) of the number of commits
254
+ per month.
255
+
256
+ NEXT: The only interval so far coded is monthly. Is that correct?
257
+ """
258
+
259
+ commits_list = list(self.commits_per_month.values())
260
+ mean = numpy.mean(commits_list)
261
+ stdev = numpy.std(commits_list)
262
+ try:
263
+ # we need the line below because of numpy
264
+ if mean == 0:
265
+ raise ZeroDivisionError
266
+ cv = stdev / mean
267
+ except ZeroDivisionError as e:
268
+ # the activity in commits is zero,
269
+ # so we will return the worst possible value, which is
270
+ # the cv for a distribution where all the commits where
271
+ # made in a single month
272
+ months = len(commits_list)
273
+ return sqrt(months - 1)
274
+
275
+ return cv
276
+
277
+ def get_developer_categories(self):
278
+ """Return the number of core, regular and casual developers"""
279
+
280
+ core = 0
281
+ regular = 0
282
+ casual = 0
283
+ regular_threshold = int(self.dev_categories_thresholds[0] * self.total_commits)
284
+ casual_threshold = int(self.dev_categories_thresholds[1] * self.total_commits)
285
+ acc_commits = 0
286
+ last_core_contribution = 0
287
+
288
+ for _, contributions in self.contributors.most_common():
289
+ acc_commits += contributions
290
+
291
+ if acc_commits <= regular_threshold or contributions > last_core_contribution:
292
+ last_core_contribution = contributions
293
+ core += 1
294
+ elif acc_commits <= casual_threshold or contributions == last_core_contribution:
295
+ regular += 1
296
+ else:
297
+ casual += 1
298
+
299
+ return {
300
+ "core": core,
301
+ "regular": regular,
302
+ "casual": casual,
303
+ }
304
+
305
+ def get_recent_organizations(self):
306
+ """Return the number of recent organizations."""
307
+
308
+ return len(self.recent_organizations)
309
+
310
+ def get_recent_contributors(self):
311
+ """Return the number of contributors from the last 365d."""
312
+
313
+ return len(self.recent_contributors)
314
+
315
+ def get_recent_commits(self) -> int:
316
+ """Return the number of commits in the last 365d."""
317
+
318
+ return self.recent_commits
319
+
320
+ def get_commits_over_periods_rate(self):
321
+ """Return the rate of commits between a recent period and the last year."""
322
+
323
+ try:
324
+ return self.recent_commits / self.total_commits
325
+ except ZeroDivisionError:
326
+ return 0.0
327
+
328
+ def get_growth_of_contributors(self):
329
+ """Return the growth of contributors by period."""
330
+
331
+ first_half = len(self.contributors_growth["first_half"])
332
+ second_half = len(self.contributors_growth["second_half"])
333
+
334
+ return second_half - first_half
335
+
336
+ def get_growth_rate_of_contributors(self):
337
+ """Return the growth of contributors by period."""
338
+
339
+ first_half = len(self.contributors_growth["first_half"])
340
+ second_half = len(self.contributors_growth["second_half"])
341
+
342
+ if first_half == 0 and second_half == 0:
343
+ return 0
344
+ elif first_half == 0 and second_half != 0:
345
+ # It increased infinitely
346
+ return second_half
347
+ else:
348
+ return (second_half - first_half) / first_half
349
+
350
+ def get_active_branch_count(self):
351
+ """Return the number of active branches."""
352
+
353
+ return len(self.active_branches)
354
+
355
+ def get_analysis_metadata(self):
356
+ """Return metadata about the analysis."""
357
+
358
+ metadata = {
359
+ "first_commit": self.first_commit,
360
+ "last_commit": self.last_commit,
361
+ "first_commit_date": None,
362
+ "last_commit_date": None,
363
+ }
364
+
365
+ if self.first_commit_date:
366
+ metadata["first_commit_date"] = self.first_commit_date.isoformat()
367
+ if self.last_commit_date:
368
+ metadata["last_commit_date"] = self.last_commit_date.isoformat()
369
+
370
+ return metadata
371
+
372
+ def get_days_since_last_commit(self):
373
+ """
374
+ Return the number of days since the last commit, if no commits
375
+ are found it returns the number of days of the monitored timeframe."""
376
+
377
+ if self.last_commit_date:
378
+ days_since_last_commit = (self.to_date - self.last_commit_date).days
379
+ elif not self.last_commit_date:
380
+ # when the repository was not active during the monitored timeframe
381
+ # we set the worst possible value within the timeframe
382
+ days_since_last_commit = (self.to_date - self.from_date).days
383
+
384
+ return days_since_last_commit
385
+
386
+ def get_casual_regular_contributors_rate(self):
387
+ """Calculate the rate between casual contributors and regular contributors."""
388
+
389
+ dev_categories = self.get_developer_categories()
390
+ core_and_regular = dev_categories["core"] + dev_categories["regular"]
391
+ casual = dev_categories["casual"]
392
+
393
+ if not core_and_regular:
394
+ # If there are no core or regular contributors, return 0
395
+ # because there shouldn't be any casual contributors.
396
+ return 0.0
397
+ else:
398
+ return casual / core_and_regular
399
+
400
+ def get_found_files(self):
401
+ """Return the files found in the repository."""
402
+
403
+ return {
404
+ "license": 1 if self.files_found["license"] > 0 else 0,
405
+ "adopters": 1 if self.files_found["adopters"] > 0 else 0,
406
+ }
407
+
408
+ def get_returning_contributors(self):
409
+ """Return the number of returning contributors by period."""
410
+
411
+ returning_contributors = 0
412
+ for author in self.returning_contributors["first_period"]:
413
+ if author in self.returning_contributors["second_period"]:
414
+ returning_contributors += 1
415
+
416
+ return returning_contributors
417
+
418
+ def _update_commit_count(self, event_data):
419
+ """Update the commit count and commits by period."""
420
+
421
+ # Update total commits
422
+ self.total_commits += 1
423
+
424
+ # Update commits by period
425
+ try:
426
+ commit_date = str_to_datetime(event_data.get("CommitDate"))
427
+ days_interval = (self.to_date - commit_date).days
428
+ except (ValueError, TypeError, InvalidDateError):
429
+ return
430
+
431
+ if days_interval <= 365:
432
+ self.recent_commits += 1
433
+
434
+ # Update commits per month
435
+ # try: ##FIXME
436
+ month_key = commit_date.strftime("%Y-%m")
437
+ self.commits_per_month[month_key] += 1
438
+ # #except (ValueError, TypeError, InvalidDateError):
439
+ # #pass
440
+
441
+ def _update_contributors(self, event_data):
442
+ author = event_data[AUTHOR_FIELD]
443
+
444
+ self.contributors[author] += 1
445
+
446
+ # Update contributor growth
447
+ try:
448
+ commit_date = event_data.get("CommitDate")
449
+ commit_date = str_to_datetime(commit_date)
450
+ except (ValueError, TypeError, InvalidDateError):
451
+ commit_date = None
452
+
453
+ if commit_date and self._half_period:
454
+ if commit_date < self._half_period:
455
+ self.contributors_growth["first_half"].add(author)
456
+ else:
457
+ self.contributors_growth["second_half"].add(author)
458
+
459
+ # Update contributors by period
460
+ if commit_date:
461
+ days_interval = (self.to_date - commit_date).days
462
+ if days_interval <= 365:
463
+ self.recent_contributors.add(author)
464
+ self.returning_contributors["second_period"].add(author)
465
+ else:
466
+ self.returning_contributors["first_period"].add(author)
467
+
468
+ def _update_organizations(self, event_data):
469
+ try:
470
+ author = event_data[AUTHOR_FIELD]
471
+ organization = author.split("@")[1][:-1]
472
+ except (IndexError, KeyError):
473
+ return
474
+
475
+ self.organizations[organization] += 1
476
+
477
+ # Update organizations by period
478
+ try:
479
+ commit_date = str_to_datetime(event_data.get("CommitDate"))
480
+ days_interval = (self.to_date - commit_date).days
481
+ except (ValueError, TypeError, InvalidDateError):
482
+ pass
483
+ else:
484
+ if days_interval <= 365:
485
+ self.recent_organizations.add(organization)
486
+
487
+ def _update_file_metrics(self, event):
488
+ if "files" not in event:
489
+ return
490
+
491
+ for file in event["files"]:
492
+ if not file["file"]:
493
+ continue
494
+
495
+ # File type metrics
496
+ if self.re_code_pattern.search(file["file"]):
497
+ self.file_types["code"] += 1
498
+ elif self.re_binary_pattern.search(file["file"]):
499
+ self.file_types["binary"] += 1
500
+ else:
501
+ self.file_types["other"] += 1
502
+
503
+ # Line added/removed metrics
504
+ if "added" in file:
505
+ try:
506
+ self.added_lines += int(file["added"])
507
+ except ValueError:
508
+ pass
509
+ if "removed" in file:
510
+ try:
511
+ self.removed_lines += int(file["removed"])
512
+ except ValueError:
513
+ pass
514
+
515
+ def _check_files_found(self, event):
516
+ """
517
+ Check if the file exists in the event data and update metrics accordingly.
518
+
519
+ To identify if a file exists, it checks the filename against
520
+ the regular expressions for license and adopters files.
521
+ When the filename matches, added and copied actions increase the count,
522
+ deleted and replaced actions decrease the count if it is the filename,
523
+ and increase if it is the new filename.
524
+ If the file count is greater than zero, it indicates that at least one
525
+ of the files exists in the repository.
526
+ """
527
+ event_type = event["type"]
528
+ data = event["data"]
529
+
530
+ if event_type == GIT_EVENT_ACTION_ADDED:
531
+ if COMPILED_LICENSE_FILE_REGEX.fullmatch(data["filename"]):
532
+ self.files_found["license"] += 1
533
+ elif COMPILED_ADOPTERS_FILE_REGEX.fullmatch(data["filename"]):
534
+ self.files_found["adopters"] += 1
535
+
536
+ elif event_type == GIT_EVENT_ACTION_DELETED:
537
+ if COMPILED_LICENSE_FILE_REGEX.fullmatch(data["filename"]):
538
+ self.files_found["license"] -= 1
539
+ elif COMPILED_ADOPTERS_FILE_REGEX.fullmatch(data["filename"]):
540
+ self.files_found["adopters"] -= 1
541
+
542
+ elif event_type == GIT_EVENT_ACTION_REPLACED:
543
+ if COMPILED_LICENSE_FILE_REGEX.fullmatch(data["filename"]):
544
+ self.files_found["license"] -= 1
545
+ elif COMPILED_ADOPTERS_FILE_REGEX.fullmatch(data["filename"]):
546
+ self.files_found["adopters"] -= 1
547
+ if COMPILED_LICENSE_FILE_REGEX.fullmatch(data["new_filename"]):
548
+ self.files_found["license"] += 1
549
+ elif COMPILED_ADOPTERS_FILE_REGEX.fullmatch(data["new_filename"]):
550
+ self.files_found["adopters"] += 1
551
+
552
+ elif event_type == GIT_EVENT_ACTION_COPIED:
553
+ if COMPILED_LICENSE_FILE_REGEX.fullmatch(data["new_filename"]):
554
+ self.files_found["license"] += 1
555
+ elif COMPILED_ADOPTERS_FILE_REGEX.fullmatch(data["new_filename"]):
556
+ self.files_found["adopters"] += 1
557
+
558
+ def _update_message_size_metrics(self, event):
559
+ message = event.get("message", "")
560
+ self.messages_sizes.append(len(message))
561
+
562
+ def _update_first_and_last_commit(self, event):
563
+ """Update last commit and first commit metadata."""
564
+
565
+ commit = event.get("commit")
566
+ commit_date = event.get("CommitDate")
567
+ if not commit_date or not commit:
568
+ return
569
+
570
+ commit_date = str_to_datetime(commit_date)
571
+
572
+ if not self.first_commit or self.first_commit_date > commit_date:
573
+ self.first_commit = commit
574
+ self.first_commit_date = commit_date
575
+
576
+ if not self.last_commit or self.last_commit_date < commit_date:
577
+ self.last_commit = commit
578
+ self.last_commit_date = commit_date
579
+
580
+ def _update_branches(self, event_data):
581
+ """Identify the refs that are branches and update the active branches."""
582
+
583
+ if "refs" not in event_data:
584
+ return
585
+
586
+ for ref in event_data["refs"]:
587
+ if "refs/heads/" not in ref:
588
+ continue
589
+
590
+ branch_name = ref.split("refs/heads/")[1]
591
+ self.active_branches.add(branch_name)
592
+
593
+
594
+ def get_repository_metrics(
595
+ repository: str,
596
+ opensearch_url: str,
597
+ opensearch_index: str,
598
+ opensearch_user: str = None,
599
+ opensearch_password: str = None,
600
+ opensearch_ca_certs: str = None,
601
+ opensearch_timeout: int = 30,
602
+ from_date: datetime.datetime = None,
603
+ to_date: datetime.datetime = None,
604
+ verify_certs: bool = True,
605
+ code_file_pattern: str | None = None,
606
+ binary_file_pattern: str | None = None,
607
+ pony_threshold: float | None = None,
608
+ elephant_threshold: float | None = None,
609
+ dev_categories_thresholds: tuple[float, float] = (0.8, 0.95),
610
+ ):
611
+ """
612
+ Get the metrics from a repository.
613
+
614
+ :param repository: Repository URI
615
+ :param opensearch_url: URL of the OpenSearch instance
616
+ :param opensearch_index: Name of the index where the data is stored
617
+ :param opensearch_user: Username to connect to OpenSearch, by default None
618
+ :param opensearch_password: Password to connect to OpenSearch, by default None
619
+ :param opensearch_ca_certs: Path to the CA certificate, by default None
620
+ :param opensearch_timeout: Timeout for the OpenSearch connection, by default 30
621
+ :param verify_certs: Boolean, verify SSL/TLS certificates, default True
622
+ :param from_date: Start date, by default None
623
+ :param to_date: End date, by default None
624
+ :param code_file_pattern: Regular expression to match code file types.
625
+ :param binary_file_pattern: Regular expression to match binary file types.
626
+ :param pony_threshold: Threshold for the pony factor
627
+ :param elephant_threshold: Threshold for the elephant factor
628
+ :param dev_categories_thresholds: Threshold for the developer categories
629
+ """
630
+
631
+ logging.debug(f"Collecting data and generating metrics for {repository}")
632
+
633
+ os_conn = connect_to_opensearch(
634
+ url=opensearch_url,
635
+ username=opensearch_user,
636
+ password=opensearch_password,
637
+ ca_certs_path=opensearch_ca_certs,
638
+ verify_certs=verify_certs,
639
+ timeout=opensearch_timeout,
640
+ )
641
+
642
+ analyzer = GitEventsAnalyzer(
643
+ from_date=from_date,
644
+ to_date=to_date,
645
+ code_file_pattern=code_file_pattern,
646
+ binary_file_pattern=binary_file_pattern,
647
+ pony_threshold=pony_threshold,
648
+ elephant_threshold=elephant_threshold,
649
+ dev_categories_thresholds=dev_categories_thresholds,
650
+ )
651
+
652
+ # Process commit events for the repository within the specified date range
653
+ events = get_repository_events(
654
+ connection=os_conn,
655
+ index_name=opensearch_index,
656
+ repository=repository,
657
+ event_type=[GIT_EVENT_COMMIT],
658
+ from_date=from_date,
659
+ to_date=to_date,
660
+ )
661
+ analyzer.process_events(events)
662
+
663
+ # Process file events for the repository, only for license and adopters files
664
+ file_regex = ADOPTERS_FILE_REGEX + r"|" + LICENSE_FILE_REGEX
665
+ file_filter = Q(
666
+ "bool",
667
+ should=[Q("regexp", data__filename=file_regex), Q("regexp", data__new_filename=file_regex)],
668
+ minimum_should_match=1,
669
+ )
670
+ events = get_repository_events(
671
+ connection=os_conn,
672
+ index_name=opensearch_index,
673
+ repository=repository,
674
+ event_type=GIT_EVENT_FILE_ACTIONS,
675
+ to_date=to_date,
676
+ additional_filter=file_filter,
677
+ )
678
+
679
+ analyzer.process_events(events)
680
+
681
+ metrics = {"metrics": {}}
682
+ metrics["metrics"]["total_commits"] = analyzer.get_commit_count()
683
+ metrics["metrics"]["total_contributors"] = analyzer.get_contributor_count()
684
+ metrics["metrics"]["total_organizations"] = analyzer.get_organization_count()
685
+ metrics["metrics"]["pony_factor"] = analyzer.get_pony_factor()
686
+ metrics["metrics"]["elephant_factor"] = analyzer.get_elephant_factor()
687
+ metrics["metrics"]["recent_organizations"] = analyzer.get_recent_organizations()
688
+ metrics["metrics"]["recent_contributors"] = analyzer.get_recent_contributors()
689
+ metrics["metrics"]["recent_commits"] = analyzer.get_recent_commits()
690
+ metrics["metrics"]["contributor_growth"] = analyzer.get_growth_of_contributors()
691
+ metrics["metrics"]["contributor_growth_rate"] = analyzer.get_growth_rate_of_contributors()
692
+ metrics["metrics"]["active_branches"] = analyzer.get_active_branch_count()
693
+ metrics["metrics"]["days_since_last_commit"] = analyzer.get_days_since_last_commit()
694
+ metrics["metrics"]["casual_regular_contributors_rate"] = analyzer.get_casual_regular_contributors_rate()
695
+ metrics["metrics"]["returning_contributors"] = analyzer.get_returning_contributors()
696
+ metrics["metrics"]["commits_over_periods_rate"] = analyzer.get_commits_over_periods_rate()
697
+ metrics["metrics"]["coefficient_of_variation"] = analyzer.get_commit_coefficient_of_variation()
698
+
699
+ if from_date and to_date:
700
+ days = (to_date - from_date).days
701
+ else:
702
+ days = 365
703
+
704
+ # Flatten two-level metrics
705
+ metrics_to_flatten = {
706
+ "file_types": analyzer.get_file_type_metrics(),
707
+ "commit_size": analyzer.get_commit_size_metrics(),
708
+ "message_size": analyzer.get_message_size_metrics(),
709
+ "developer_categories": analyzer.get_developer_categories(),
710
+ "commits_per": analyzer.get_commit_frequency_metrics(days),
711
+ "found_file": analyzer.get_found_files(),
712
+ }
713
+
714
+ for prefix, metrics_set in metrics_to_flatten.items():
715
+ for name, value in metrics_set.items():
716
+ metrics["metrics"][prefix + "_" + name] = value
717
+
718
+ metrics["metadata"] = analyzer.get_analysis_metadata()
719
+ metrics["metrics"] = dict(sorted(metrics["metrics"].items()))
720
+
721
+ return metrics
722
+
723
+
724
+ def get_repository_events(
725
+ connection: OpenSearch,
726
+ index_name: str,
727
+ repository: str,
728
+ event_type: list[str] | None = None,
729
+ from_date: datetime.datetime | None = None,
730
+ to_date: datetime.datetime | None = None,
731
+ additional_filter: Any | None = None,
732
+ ) -> iter(dict[str, Any]):
733
+ """
734
+ Returns the events for a repository within a specified date range and event type.
735
+
736
+ :param connection: OpenSearch connection object
737
+ :param index_name: Name of the alias where Git data is stored in BAP
738
+ :param repository: Name of the repository to filter commits
739
+ :param event_type: List of event types to filter, e.g., [GIT_EVENT_COMMIT]
740
+ :param from_date: Start date, by default None
741
+ :param to_date: End date, by default None
742
+ :param additional_filter: Additional filter to apply to the search query, by default None
743
+ """
744
+ s = Search(using=connection, index=index_name).filter("match", source=repository)
745
+
746
+ if event_type:
747
+ s = s.filter("terms", type=event_type)
748
+
749
+ date_range = _format_date(from_date, to_date)
750
+ if date_range:
751
+ s = s.filter("range", time=date_range)
752
+
753
+ if additional_filter:
754
+ s = s.filter(additional_filter)
755
+
756
+ return s.scan()
757
+
758
+
759
+ def connect_to_opensearch(
760
+ url: str,
761
+ username: str | None = None,
762
+ password: str | None = None,
763
+ ca_certs_path: str | None = None,
764
+ verify_certs: bool = True,
765
+ max_retries: int = 3,
766
+ timeout: int = 30,
767
+ ) -> OpenSearch:
768
+ """
769
+ Connect to an OpenSearch instance using the given parameters.
770
+
771
+ :param url: URL of the OpenSearch instance
772
+ :param username: Username to connect to OpenSearch
773
+ :param password: Password to connect to OpenSearch
774
+ :param ca_certs_path: Path to the CA certificate
775
+ :param verify_certs: Boolean, verify SSL/TLS certificates
776
+ :param max_retries: Maximum number of retries in case of timeout
777
+ :param timeout: Timeout for each request in seconds
778
+
779
+ :return: OpenSearch connection
780
+ """
781
+ auth = None
782
+ if username and password:
783
+ auth = (username, password)
784
+
785
+ os_conn = OpenSearch(
786
+ hosts=[url],
787
+ http_auth=auth,
788
+ http_compress=True,
789
+ verify_certs=verify_certs,
790
+ ssl_assert_hostname=False,
791
+ ssl_show_warn=False,
792
+ ca_certs=ca_certs_path,
793
+ max_retries=max_retries,
794
+ retry_on_timeout=True,
795
+ timeout=timeout,
796
+ )
797
+
798
+ return os_conn
799
+
800
+
801
+ def _format_date(from_date: datetime.datetime | None, to_date: datetime.datetime | None) -> dict:
802
+ """
803
+ Format the date range for the OpenSearch query.
804
+
805
+ :param from_date: Start date
806
+ :param to_date: End date
807
+ """
808
+ date_range = {}
809
+ if from_date:
810
+ date_range["gte"] = from_date
811
+ if to_date:
812
+ date_range["lt"] = to_date
813
+
814
+ return date_range