Skip to content

Make Project -> ForeignKey -> RemoteRepository #8259

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 17, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions docs/api/v3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1713,12 +1713,12 @@ Remote Repository listing

.. code-tab:: bash

$ curl -H "Authorization: Token <token>" https://readthedocs.org/api/v3/remote/repositories/?expand=project,organization
$ curl -H "Authorization: Token <token>" https://readthedocs.org/api/v3/remote/repositories/?expand=projects,remote_organization

.. code-tab:: python

import requests
URL = 'https://readthedocs.org/api/v3/remote/repositories/?expand=project,organization'
URL = 'https://readthedocs.org/api/v3/remote/repositories/?expand=projects,remote_organization'
TOKEN = '<token>'
HEADERS = {'Authorization': f'token {TOKEN}'}
response = requests.get(URL, headers=HEADERS)
Expand All @@ -1730,11 +1730,11 @@ Remote Repository listing

{
"count": 20,
"next": "api/v3/remote/repositories/?expand=project,organization&limit=10&offset=10",
"next": "api/v3/remote/repositories/?expand=projects,remote_organization&limit=10&offset=10",
"previous": null,
"results": [
{
"organization": {
"remote_organization": {
"avatar_url": "https://avatars.githubusercontent.com/u/12345?v=4",
"created": "2019-04-29T10:00:00Z",
"modified": "2019-04-29T12:00:00Z",
Expand All @@ -1744,7 +1744,7 @@ Remote Repository listing
"url": "https://github.com/organization",
"vcs_provider": "github"
},
"project": {
"project": [{
"id": 12345,
"name": "project",
"slug": "project",
Expand Down Expand Up @@ -1787,7 +1787,7 @@ Remote Repository listing
"redirects": "/api/v3/projects/project/redirects/",
"translations": "/api/v3/projects/project/translations/"
}
}
}],
"avatar_url": "https://avatars3.githubusercontent.com/u/test-organization?v=4",
"clone_url": "https://github.com/organization/project.git",
"created": "2019-04-29T10:00:00Z",
Expand All @@ -1814,7 +1814,7 @@ Remote Repository listing
:query string vcs_provider: return remote repositories for specific vcs provider (``github``, ``gitlab`` or ``bitbucket``)
:query string organization: return remote repositories for specific remote organization (using remote organization ``slug``)
:query string expand: allows to add/expand some extra fields in the response.
Allowed values are ``project`` and ``organization``.
Allowed values are ``projects`` and ``remote_organization``.
Multiple fields can be passed separated by commas.
Comment on lines 1816 to 1818
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@agjohnson this a change in the API request/response required to make sense with the new relation. It also reserves ?expand=organization to be used for Organization objects.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was going to say we should keep project around for backwards compatibility, but this API should really only be internal use anyways. So yeah, agreed this seems fine.


:requestheader Authorization: token to authenticate.
Expand Down
6 changes: 3 additions & 3 deletions readthedocs/api/v3/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -950,11 +950,11 @@ class Meta:
]
read_only_fields = fields
expandable_fields = {
'organization': (
'remote_organization': (
RemoteOrganizationSerializer, {'source': 'organization'}
),
'project': (
ProjectSerializer, {'source': 'project'}
'projects': (
ProjectSerializer, {'source': 'projects', 'many': True}
)
}

Expand Down
22 changes: 11 additions & 11 deletions readthedocs/api/v3/tests/responses/remoterepositories-list.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,9 @@
"html_url": "https://github.com/rtd/project",
"modified": "2019-04-29T12:00:00Z",
"name": "project",
"organization": {
"avatar_url": "https://avatars.githubusercontent.com/u/366329?v=4",
"created": "2019-04-29T10:00:00Z",
"modified": "2019-04-29T12:00:00Z",
"name": "Read the Docs",
"pk": 1,
"slug": "readthedocs",
"url": "https://github.com/readthedocs",
"vcs_provider": "github"
},
"pk": 1,
"private": false,
"project": {
"projects": [{
"_links": {
"_self": "https://readthedocs.org/api/v3/projects/project/",
"builds": "https://readthedocs.org/api/v3/projects/project/builds/",
Expand Down Expand Up @@ -58,6 +48,16 @@
"versions": "https://readthedocs.org/projects/project/versions/"
},
"users": [{ "username": "testuser" }]
}],
"remote_organization": {
"avatar_url": "https://avatars.githubusercontent.com/u/366329?v=4",
"created": "2019-04-29T10:00:00Z",
"modified": "2019-04-29T12:00:00Z",
"name": "Read the Docs",
"pk": 1,
"slug": "readthedocs",
"url": "https://github.com/readthedocs",
"vcs_provider": "github"
},
"ssh_url": "[email protected]:rtd/project.git",
"vcs": "git",
Expand Down
11 changes: 6 additions & 5 deletions readthedocs/api/v3/tests/test_remoterepositories.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ def setUp(self):

self.remote_repository = fixture.get(
RemoteRepository,
project=self.project,
organization=self.remote_organization,
created=self.created,
modified=self.modified,
Expand All @@ -49,6 +48,8 @@ def setUp(self):
default_branch="master",
private=False
)
self.remote_repository.projects.add(self.project)

social_account = fixture.get(SocialAccount, user=self.me, provider=GITHUB)
fixture.get(
RemoteRepositoryRelation,
Expand All @@ -70,8 +71,8 @@ def test_remote_repository_list(self):
reverse('remoterepositories-list'),
{
'expand': (
'project,'
'organization'
'projects,'
'remote_organization'
)
}
)
Expand All @@ -88,8 +89,8 @@ def test_remote_repository_list_name_filter(self):
reverse('remoterepositories-list'),
{
'expand': (
'project,'
'organization'
'projects,'
'remote_organization'
),
'name': 'proj'
}
Expand Down
12 changes: 5 additions & 7 deletions readthedocs/api/v3/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -451,8 +451,8 @@ class RemoteRepositoryViewSet(
queryset = RemoteRepository.objects.all()
permission_classes = (IsAuthenticated,)
permit_list_expands = [
'organization',
'project'
'remote_organization',
'projects'
]

def get_queryset(self):
Expand All @@ -466,13 +466,11 @@ def get_queryset(self):
)
)

if is_expanded(self.request, 'organization'):
if is_expanded(self.request, 'remote_organization'):
queryset = queryset.select_related('organization')

if is_expanded(self.request, 'project'):
queryset = queryset.select_related('project').prefetch_related(
'project__users',
)
if is_expanded(self.request, 'projects'):
queryset = queryset.prefetch_related('projects__users')

return queryset.order_by('organization__name', 'full_name').distinct()

Expand Down
5 changes: 2 additions & 3 deletions readthedocs/builds/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ def send_build_status(build_pk, commit, status, link_to_build=False):
service_class = build.project.git_service_class()
users = build.project.users.all()

try:
if build.project.remote_repository:
remote_repository = build.project.remote_repository
remote_repository_relations = (
remote_repository.remote_repository_relations.filter(
Expand Down Expand Up @@ -406,8 +406,7 @@ def send_build_status(build_pk, commit, status, link_to_build=False):
relation.user.username,
)
return True

except RemoteRepository.DoesNotExist:
else:
log.warning(
'Project does not have a RemoteRepository. project=%s',
build.project.slug,
Expand Down
2 changes: 1 addition & 1 deletion readthedocs/oauth/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class RemoteRepositoryAdmin(admin.ModelAdmin):

"""Admin configuration for the RemoteRepository model."""

raw_id_fields = ('project', 'organization',)
raw_id_fields = ('organization',)


class RemoteRepositoryRelationAdmin(admin.ModelAdmin):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Generated by Django 2.2.22 on 2021-06-14 15:42

from django.db import migrations


def migrate_data(apps, schema_editor):
RemoteRepository = apps.get_model('oauth', 'RemoteRepository')
queryset = RemoteRepository.objects.filter(project__isnull=False).select_related('project')
for rr in queryset.iterator():
rr.project.remote_repository = rr
rr.save()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Took me a second to follow this logic, but I think this looks good. I suppose I would have concerns about performance here, we will have a few thousand remote repositories to step through individually.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just checked this: 22k. We should be fine.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I double-checked this logic and it didn't work.

rr.project.remote_repository = rr

That doesn't seem to keep the relation.

I also tried,

rr.project.remote_repository_id = rr.pk

I don't understand why.

Copy link
Member Author

@humitos humitos Jun 17, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Meh, I found that I was just saving the wrong object.

We need either:

rr.project.save()

or

rr.projects.add(rr.project)

However, both are producing an error that I'm not sure to understand 😞

database_1  | 2021-06-17 12:05:45.877 UTC [193] ERROR:  cannot ALTER TABLE "projects_project" because it has pending trigger events
database_1  | 2021-06-17 12:05:45.877 UTC [193] STATEMENT:  SET CONSTRAINTS "oauth_remotereposito_project_id_246c363d_fk_projects_" IMMEDIATE; ALTER TABLE "oauth_remoterepository_2020" DROP CONSTRAINT "oauth_remotereposito_project_id_246c363d_fk_projects_"



class Migration(migrations.Migration):

dependencies = [
('oauth', '0013_create_new_table_for_remote_repository_normalization'),
('projects', '0076_project_remote_repository'),
]

operations = [
migrations.RunPython(migrate_data),
migrations.RemoveField(
model_name='remoterepository',
name='project',
),
]
7 changes: 0 additions & 7 deletions readthedocs/oauth/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,13 +124,6 @@ class RemoteRepository(TimeStampedModel):
blank=True,
on_delete=models.CASCADE,
)
project = models.OneToOneField(
Project,
on_delete=models.SET_NULL,
related_name='remote_repository',
null=True,
blank=True,
)
name = models.CharField(_('Name'), max_length=255)
full_name = models.CharField(
_('Full Name'),
Expand Down
4 changes: 2 additions & 2 deletions readthedocs/oauth/services/gitlab.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ class GitLabService(Service):
def _get_repo_id(self, project):
# The ID or URL-encoded path of the project
# https://docs.gitlab.com/ce/api/README.html#namespaced-path-encoding
try:
if project.remote_repository:
repo_id = project.remote_repository.remote_id
except Project.remote_repository.RelatedObjectDoesNotExist:
else:
# Handle "Manual Import" when there is no RemoteRepository
# associated with the project. It only works with gitlab.com at the
# moment (doesn't support custom gitlab installations)
Expand Down
2 changes: 1 addition & 1 deletion readthedocs/projects/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ class ProjectAdmin(admin.ModelAdmin):
DomainInline,
]
readonly_fields = ('pub_date', 'feature_flags',)
raw_id_fields = ('users', 'main_language_project')
raw_id_fields = ('users', 'main_language_project', 'remote_repository')
actions = [
'send_owner_email',
'ban_owner',
Expand Down
2 changes: 1 addition & 1 deletion readthedocs/projects/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def save(self, commit=True):
remote_repo = self.cleaned_data.get('remote_repository', None)
if remote_repo:
if commit:
remote_repo.project = self.instance
remote_repo.projects.add(self.instance)
remote_repo.save()
else:
instance.remote_repository = remote_repo
Expand Down
20 changes: 20 additions & 0 deletions readthedocs/projects/migrations/0076_project_remote_repository.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Generated by Django 2.2.22 on 2021-06-14 15:42

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('oauth', '0013_create_new_table_for_remote_repository_normalization'),
('projects', '0075_change_mkdocs_name'),
]

operations = [
migrations.AddField(
model_name='project',
name='remote_repository',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='projects', to='oauth.RemoteRepository'),
),
]
8 changes: 8 additions & 0 deletions readthedocs/projects/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,14 @@ class Project(models.Model):
objects = ProjectQuerySet.as_manager()
all_objects = models.Manager()

remote_repository = models.ForeignKey(
'oauth.RemoteRepository',
on_delete=models.SET_NULL,
related_name='projects',
null=True,
blank=True,
)

# Property used for storing the latest build for a project when prefetching
LATEST_BUILD_CACHE = '_latest_build'

Expand Down
6 changes: 4 additions & 2 deletions readthedocs/rtd_tests/tests/test_celery.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,8 @@ def test_send_build_status_with_remote_repo_github(self, send_build_status):
self.project.save()

social_account = get(SocialAccount, user=self.eric, provider='gitlab')
remote_repo = get(RemoteRepository, project=self.project)
remote_repo = get(RemoteRepository)
remote_repo.projects.add(self.project)
get(
RemoteRepositoryRelation,
remote_repository=remote_repo,
Expand Down Expand Up @@ -417,7 +418,8 @@ def test_send_build_status_with_remote_repo_gitlab(self, send_build_status):
self.project.save()

social_account = get(SocialAccount, user=self.eric, provider='gitlab')
remote_repo = get(RemoteRepository, project=self.project)
remote_repo = get(RemoteRepository)
remote_repo.projects.add(self.project)
get(
RemoteRepositoryRelation,
remote_repository=remote_repo,
Expand Down
2 changes: 1 addition & 1 deletion readthedocs/rtd_tests/tests/test_oauth_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,11 @@ def test_sync_delete_stale(self, mock_request):
project = fixture.get(Project)
repo_3 = fixture.get(
RemoteRepository,
project=project,
full_name='organization/project-linked-repository',
remote_id='54321',
vcs_provider=GITHUB
)
repo_3.projects.add(project)
fixture.get(
RemoteRepositoryRelation,
remote_repository=repo_3,
Expand Down