|
| 1 | +"""Github app label model.""" |
| 2 | + |
| 3 | +from django.db import models |
| 4 | +from django.template.defaultfilters import pluralize |
| 5 | + |
| 6 | +from apps.common.models import BulkSaveModel, TimestampedModel |
| 7 | + |
| 8 | +TOP_CONTRIBUTORS_LIMIT = 20 |
| 9 | + |
| 10 | + |
| 11 | +class RepositoryContributor(BulkSaveModel, TimestampedModel): |
| 12 | + """Repository contributor model.""" |
| 13 | + |
| 14 | + class Meta: |
| 15 | + db_table = "github_repository_contributors" |
| 16 | + verbose_name_plural = "Repository contributors" |
| 17 | + |
| 18 | + contributions_count = models.PositiveIntegerField(verbose_name="Contributions", default=0) |
| 19 | + |
| 20 | + # FKs. |
| 21 | + repository = models.ForeignKey( |
| 22 | + "github.Repository", |
| 23 | + verbose_name="Repository", |
| 24 | + on_delete=models.CASCADE, |
| 25 | + ) |
| 26 | + user = models.ForeignKey( |
| 27 | + "github.User", |
| 28 | + verbose_name="User", |
| 29 | + on_delete=models.CASCADE, |
| 30 | + ) |
| 31 | + |
| 32 | + def __str__(self): |
| 33 | + """Repository contributor human readable representation.""" |
| 34 | + return ( |
| 35 | + f"{self.user} has made {self.contributions_count} " |
| 36 | + f"contribution{pluralize(self.contributions_count)} to {self.repository}" |
| 37 | + ) |
| 38 | + |
| 39 | + def from_github(self, gh_label): |
| 40 | + """Update instance based on GitHub contributor data.""" |
| 41 | + field_mapping = { |
| 42 | + "contributions_count": "contributions", |
| 43 | + } |
| 44 | + |
| 45 | + # Direct fields. |
| 46 | + for model_field, gh_field in field_mapping.items(): |
| 47 | + value = getattr(gh_label, gh_field) |
| 48 | + if value is not None: |
| 49 | + setattr(self, model_field, value) |
| 50 | + |
| 51 | + @staticmethod |
| 52 | + def bulk_save(repository_contributors): |
| 53 | + """Bulk save repository contributors.""" |
| 54 | + BulkSaveModel.bulk_save(RepositoryContributor, repository_contributors) |
| 55 | + |
| 56 | + @staticmethod |
| 57 | + def update_data(gh_contributor, repository, user, save=True): |
| 58 | + """Update repository contributor data.""" |
| 59 | + try: |
| 60 | + repository_contributor = RepositoryContributor.objects.get( |
| 61 | + repository=repository, |
| 62 | + user=user, |
| 63 | + ) |
| 64 | + except RepositoryContributor.DoesNotExist: |
| 65 | + repository_contributor = RepositoryContributor( |
| 66 | + repository=repository, |
| 67 | + user=user, |
| 68 | + ) |
| 69 | + repository_contributor.from_github(gh_contributor) |
| 70 | + |
| 71 | + if save: |
| 72 | + repository_contributor.save() |
| 73 | + |
| 74 | + return repository_contributor |
0 commit comments