-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathserializers.py
89 lines (74 loc) · 3.1 KB
/
serializers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
from rest_framework import exceptions, serializers
from core.models import Commit
from labelanalysis.models import (
LabelAnalysisProcessingError,
LabelAnalysisRequest,
LabelAnalysisRequestState,
)
class CommitFromShaSerializerField(serializers.Field):
def __init__(self, *args, **kwargs):
self.accepts_fallback = kwargs.pop("accepts_fallback", False)
super().__init__(*args, **kwargs)
def to_representation(self, commit):
return commit.commitid
def to_internal_value(self, commit_sha):
commit = Commit.objects.filter(
repository__in=self.context["request"].auth.get_repositories(),
commitid=commit_sha,
).first()
if commit is None:
raise exceptions.NotFound(f"Commit {commit_sha[:7]} not found.")
if commit.staticanalysissuite_set.exists():
return commit
if not self.accepts_fallback:
raise serializers.ValidationError("No static analysis found")
attempted_commits = []
for _ in range(10):
attempted_commits.append(commit.commitid)
commit = commit.parent_commit
if commit is None:
raise serializers.ValidationError(
f"No possible commits have static analysis sent. Attempted commits: {','.join(attempted_commits)}"
)
if commit.staticanalysissuite_set.exists():
return commit
raise serializers.ValidationError(
f"No possible commits have static analysis sent. Attempted too many commits: {','.join(attempted_commits)}"
)
class LabelAnalysisProcessingErrorSerializer(serializers.ModelSerializer):
class Meta:
model = LabelAnalysisProcessingError
fields = ("error_code", "error_params")
read_only_fields = ("error_code", "error_params")
class ProcessingErrorList(serializers.ListField):
child = LabelAnalysisProcessingErrorSerializer()
def to_representation(self, data):
data = data.select_related(
"label_analysis_request",
).all()
return super().to_representation(data)
class LabelAnalysisRequestSerializer(serializers.ModelSerializer):
base_commit = CommitFromShaSerializerField(required=True, accepts_fallback=True)
head_commit = CommitFromShaSerializerField(required=True, accepts_fallback=False)
state = serializers.SerializerMethodField()
errors = ProcessingErrorList(required=False)
def validate(self, data):
if data["base_commit"] == data["head_commit"]:
raise serializers.ValidationError(
{"base_commit": "Base and head must be different commits"}
)
return data
class Meta:
model = LabelAnalysisRequest
fields = (
"base_commit",
"head_commit",
"requested_labels",
"result",
"state",
"external_id",
"errors",
)
read_only_fields = ("result", "external_id", "errors")
def get_state(self, obj):
return LabelAnalysisRequestState.enum_from_int(obj.state_id).name.lower()