Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def validate(self, data):
if hasattr(self, 'initial_data'):
validate_unknown_fields(self.initial_data, self.fields)
repository = data.pop('repository', None)
repository_version = data.get('repository_version')
if not repository and not repository_version:
raise serializers.ValidationError(
_("Either the 'repository' or 'repository_version' need to be specified"))
elif not repository and repository_version:
return data
elif repository and not repository_version:
version = models.RepositoryVersion.latest(repository)
if version:
new_data = {'repository_version': version}
new_data.update(data)
return new_data
else:
raise serializers.ValidationError(
detail=_('Repository has no version available to publish'))
raise serializers.ValidationError(
_("Either the 'repository' or 'repository_version' need to be specified "
"but not both.")
path_param = None
if "}" in path:
resource_path = "%s}/" % path.rsplit(sep="}", maxsplit=1)[0]
if resource_path in endpoints:
view = endpoints[resource_path][0]
if not hasattr(view, "queryset") or view.queryset is None:
if hasattr(view, "model"):
resource_model = view.model
else:
continue
else:
resource_model = view.queryset.model
resource_name = self.get_parameter_name(resource_model)
prefix_ = None
if issubclass(resource_model, RepositoryVersion):
prefix_ = view_cls.parent_viewset.endpoint_name
param_name = self.get_parameter_slug_from_model(resource_model, prefix_)
if resource_path in resources:
path = path.replace(resource_path, "{%s}" % resources[resource_path])
else:
resources[resource_path] = param_name
resource_example[resource_path] = self.get_example_uri(path)
path = path.replace(resource_path, "{%s}" % resources[resource_path])
example = resource_example[resource_path]
resource_description = self.get_resource_description(resource_name, example)
path_param = openapi.Parameter(
name=param_name,
description=resource_description,
required=True,
in_=openapi.IN_PATH,
type=openapi.TYPE_STRING,
@classmethod
def latest(cls, repository):
"""
Get the latest RepositoryVersion on a repository
Args:
repository (pulpcore.plugin.models.Repository): to get the latest version of
Returns:
pulpcore.plugin.repository.RepositoryVersion: The latest RepositoryVersion
"""
with suppress(models.RepositoryVersion.DoesNotExist):
model = repository.versions.exclude(complete=False).latest()
return RepositoryVersion(model)
that the content set for each version stays the same.
There must be a newer version to squash into. If we deleted the latest version, the next content
change would create a new one of the same number, which would violate the immutability
guarantee.
Args:
pk (uuid): the primary key for a RepositoryVersion to delete
Raises:
models.RepositoryVersion.DoesNotExist: if there is not a newer version to squash into.
TODO: something more friendly
"""
with transaction.atomic():
try:
version = models.RepositoryVersion.objects.get(pk=pk)
except models.RepositoryVersion.DoesNotExist:
log.info(_("The repository version was not found. Nothing to do."))
return
log.info(
_("Deleting and squashing version %(v)d of repository %(r)s"),
{"v": version.number, "r": version.repository.name},
)
version.delete()
def fs_repo_version_export(exporter_pk, repo_version_pk):
"""
Export a repository version to the file system.
Args:
exporter_pk (str): FilesystemExporter pk
repo_version_pk (str): RepositoryVersion pk
"""
exporter = Exporter.objects.get(pk=exporter_pk).cast()
repo_version = RepositoryVersion.objects.get(pk=repo_version_pk)
log.info(
_(
"Exporting: file_system_exporter={exporter}, repo_version={repo_version}, path=path"
).format(exporter=exporter.name, repo_version=repo_version.pk, path=exporter.path)
)
exporter.export_repository_version(repo_version)
There must be a newer version to squash into. If we deleted the latest version, the next content
change would create a new one of the same number, which would violate the immutability
guarantee.
Args:
pk (uuid): the primary key for a RepositoryVersion to delete
Raises:
models.RepositoryVersion.DoesNotExist: if there is not a newer version to squash into.
TODO: something more friendly
"""
with transaction.atomic():
try:
version = models.RepositoryVersion.objects.get(pk=pk)
except models.RepositoryVersion.DoesNotExist:
log.info(_("The repository version was not found. Nothing to do."))
return
log.info(
_("Deleting and squashing version %(v)d of repository %(r)s"),
{"v": version.number, "r": version.repository.name},
)
version.delete()
class RepositoryVersionViewSet(NamedModelViewSet,
mixins.CreateModelMixin,
mixins.UpdateModelMixin,
mixins.RetrieveModelMixin,
mixins.ListModelMixin,
mixins.DestroyModelMixin):
endpoint_name = 'versions'
nest_prefix = 'repositories'
router_lookup = 'version'
lookup_field = 'number'
parent_viewset = RepositoryViewSet
parent_lookup_kwargs = {'repository_pk': 'repository__pk'}
serializer_class = RepositoryVersionSerializer
queryset = RepositoryVersion.objects.exclude(complete=False)
filterset_class = RepositoryVersionFilter
filter_backends = (OrderingFilter, DjangoFilterBackend)
ordering = ('-number',)
@swagger_auto_schema(operation_description="Trigger an asynchronous task to delete "
"a repositroy version.",
responses={202: AsyncOperationResponseSerializer})
def destroy(self, request, repository_pk, number):
"""
Queues a task to handle deletion of a RepositoryVersion
"""
version = self.get_object()
async_result = enqueue_with_reservation(
tasks.repository.delete_version,
[version.repository], kwargs={'pk': version.pk}
)
def create(cls, repository):
"""
Create a new RepositoryVersion
Args:
repository (pulpcore.plugin.models.Repository): to create a new version of
Returns:
pulpcore.plugin.repository.RepositoryVersion: The Created RepositoryVersion
"""
assert get_current_task_id() is not None, _('RepositoryVersion creation must be run inside '
'a task')
with transaction.atomic():
version = models.RepositoryVersion(
repository=repository,
number=repository.last_version + 1)
repository.last_version = version.number
repository.save()
version.save()
resource = models.CreatedResource(content_object=version)
resource.save()
return cls(version)
required=False,
help_text=_(
"A repository version whose content was used as the initial set of content "
"for this repository version"
),
)
content_summary = ContentSummarySerializer(
help_text=_(
"Various count summaries of the content in the version and the HREF to view " "them."
),
source="*",
read_only=True,
)
class Meta:
model = models.RepositoryVersion
fields = ModelSerializer.Meta.fields + (
"pulp_href",
"number",
"base_version",
"content_summary",
)
class RepositoryAddRemoveContentSerializer(ModelSerializer, NestedHyperlinkedModelSerializer):
add_content_units = serializers.ListField(
help_text=_(
"A list of content units to add to a new repository version. This content is "
"added after remove_content_units are removed."
),
required=False,
)
)
class RepositoryVersionSerializer(ModelSerializer, NestedHyperlinkedModelSerializer):
_href = NestedIdentityField(
view_name='versions-detail',
lookup_field='number', parent_lookup_kwargs={'repository_pk': 'repository__pk'},
)
number = serializers.IntegerField(
read_only=True
)
base_version = NestedRelatedField(
required=False,
help_text=_('A repository version whose content was used as the initial set of content '
'for this repository version'),
queryset=models.RepositoryVersion.objects.all(),
view_name='versions-detail',
lookup_field='number',
parent_lookup_kwargs={'repository_pk': 'repository__pk'},
)
content_hrefs = serializers.SerializerMethodField(
help_text=_('A mapping of the types of content in this version, and the HREF to view '
'them.'),
read_only=True,
)
content_added_hrefs = serializers.SerializerMethodField(
help_text=_('A mapping of the types of content added in this version, and the HREF to '
'view them.'),
read_only=True,
)
content_removed_hrefs = serializers.SerializerMethodField(
help_text=_('A mapping of the types of content removed from this version, and the HREF '