summaryrefslogtreecommitdiff
path: root/kodereviewer/models/reviews.py
blob: 81860fca2b44b36202d068d735df332b00e2bec5 (plain)
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
from dataclasses import dataclass, field
from enum import auto, IntEnum
from logging import getLogger
from typing import Optional, Self, Union

from PySide6.QtCore import QAbstractItemModel, QAbstractListModel, QByteArray, QModelIndex, QObject, QPersistentModelIndex, QStandardPaths, QUrl, Qt, Signal, Slot, Property
from PySide6.QtQml import QmlElement

from kodereviewer.data import PullRequest, ReviewComment

QML_IMPORT_NAME = "org.deprecated.kodereviewer"
QML_IMPORT_MAJOR_VERSION = 1

logger = getLogger(__name__)


class Roles(IntEnum):
    Body = Qt.ItemDataRole.UserRole + 1
    CreatedAt = auto()
    UpdatedAt = auto()
    Username = auto()
    AvatarUrl = auto()
    Diff = auto()
    Line = auto()


# List model

@dataclass
class Thread(QObject):
    id: int
    diff: str = ''
    reviews: list[ReviewComment] = field(default_factory=list)

    def review_ids(self) -> list[int]:
        return [review._id for review in self.reviews]


class ReviewModel(QAbstractListModel):
    _pull_request: Optional[PullRequest]
    threads: list[Thread]

    class Roles(IntEnum):
        Id = Qt.ItemDataRole.UserRole + 1
        Diff = auto()
        Reviews = auto()

    def  __init__(self):
        super().__init__()
        self._pull_request = None
        self.threads = []

    pullRequestChanged = Signal()

    def get_pull_request(self) -> Optional[PullRequest]:
        return self._pull_request

    def set_pull_request(self, pull_request: Optional[PullRequest]) -> None:
        if pull_request is None:
            return

        if self._pull_request is not None and self._pull_request == pull_request:
            return

        self.beginResetModel()
        self._pull_request = pull_request
        self._pull_request.reviewsLoaded.connect(self._reset_model)
        self.endResetModel()
        self.pullRequestChanged.emit()

    pullRequest = Property(PullRequest, fget=get_pull_request, fset=set_pull_request,
                           notify=pullRequestChanged)

    def _reset_model(self):
        assert self._pull_request is not None
        self.beginResetModel()
        self.load_reviews(self._pull_request._reviews)
        self.endResetModel()

    def load_reviews(self, reviews: list[ReviewComment]):
        self.mapping: dict[int, Thread] = {}
        for review in reviews:
            logger.info('Processing %d', review.id)
            if review._in_reply_to is not None:
                thread = self.mapping[review._in_reply_to]
            else:
                if review.id not in self.mapping:
                    self.mapping[review._id] = Thread(id=review._id, diff=review._diff)
                    thread = self.mapping[review._id]
                else:
                    thread = self.mapping[review._id]

            thread.reviews.append(review)

        self.threads = list(self.mapping.values())

    def data(self,
             index: QModelIndex | QPersistentModelIndex,
             role: int = Qt.ItemDataRole.DisplayRole) -> object:

        if self._pull_request is None:
            return None

        thread = self.threads[index.row()]

        if role == self.Roles.Id:
            return thread.id
        if role == self.Roles.Diff:
            return thread.diff
        if role == self.Roles.Reviews:
            return thread.reviews
        if role == Qt.ItemDataRole.DisplayRole:
            return f'Thread #{thread.id}'

        return None


    def rowCount(self, parent: QModelIndex | QPersistentModelIndex = QModelIndex()) -> int:
        if self._pull_request is None:
            return 0

        return len(self.threads)

    def roleNames(self) -> dict[int, QByteArray]:
        return {
            self.Roles.Id: QByteArray(b'id'),
            self.Roles.Diff: QByteArray(b'diff'),
            self.Roles.Reviews: QByteArray(b'reviews'),
        }


# Tree Model

@dataclass
class ThreadItem:
    parent: "Root"
    id: int
    reviews: list["ReviewItem"] = field(default_factory=list)

    def data(self, role: int):
        return None


@dataclass
class ReviewItem:
    parent: ThreadItem
    id: int
    review: ReviewComment

    def data(self, role: int):

        if role == Roles.Body:
            return self.review._body
        if role == Roles.CreatedAt:
            return self.review._created_at.strftime("%Y-%M-%d %H:%m")
        if role == Roles.UpdatedAt:
            return self.review._updated_at.strftime("%Y-%M-%d %H:%m")
        if role == Roles.Username:
            return self.review._.username
        if role == Roles.AvatarUrl:
            return self.review._.avatar_url
        if role == Roles.Diff:
            return self.review.diff
        if role == Roles.Line:
            return self.review.line
        if role == Qt.ItemDataRole.DisplayRole:
            return self.review._body
        return None


@dataclass
class Root:
    threads: list[ThreadItem] = field(default_factory=list)

    def data(self, role: int):
        return None


Item = Union[Root, ThreadItem, ReviewItem]

@QmlElement
class TreeReviewModel(QAbstractItemModel):

    _pull_request: Optional[PullRequest]
    root: Root

    def __init__(self):
        super().__init__()
        self._pull_request = None
        self.root = Root()

    def get_pull_request(self) -> Optional[PullRequest]:
        return self._pull_request

    def set_pull_request(self, pull_request: Optional[PullRequest]) -> None:
        if pull_request is None:
            return

        if self._pull_request is not None and self._pull_request == pull_request:
            return

        self.beginResetModel()
        self._pull_request = pull_request
        self._pull_request.reviewsLoaded.connect(self._reset_model)
        self.endResetModel()
        self.pullRequestChanged.emit()

    pullRequestChanged = Signal()
    pullRequest = Property(PullRequest, fget=get_pull_request, fset=set_pull_request,
                           notify=pullRequestChanged)

    def load_reviews(self, reviews: list[ReviewComment]):
        mapping: dict[int, ThreadItem] = {}
        for review in reviews:
            if review.id not in mapping:
                thread = ThreadItem(self.root, review.id)
            else:
                thread = mapping[review.id]
            thread.reviews.append(ReviewItem(thread, review.id, review))

    def _reset_model(self) -> None:
        if self._pull_request is None:
            return

        self.beginResetModel()
        self.load_reviews(self._pull_request._reviews)
        self.endResetModel()

    def index(self, row: int, column: int,
              parent: QModelIndex | QPersistentModelIndex = QModelIndex()) -> QModelIndex:
        if not self.hasIndex(row, column, parent):
            return QModelIndex()
        if not parent.isValid():
            if 0 <= row < len(self.root.threads):
                return self.createIndex(row, column, self.root.threads[row])
        else:
            item: Root | ThreadItem = parent.internalPointer()
            if isinstance(item, Root):
                if 0 <= row < len(self.root.threads):
                    return self.createIndex(row, column, self.root.threads[row])
            else:
                if 0 <= row < len(item.reviews):
                    return self.createIndex(row, column, item.reviews[row])
        return QModelIndex()

    def parent(self, index: QModelIndex) -> QModelIndex:
        if not index.isValid():
            return QModelIndex()
        item: Item = index.internalPointer()

        if isinstance(item, Root):
            return QModelIndex()
        if isinstance(item, ThreadItem):
            return self.createIndex(self.root.threads.index(item), 0, self.root)
        if isinstance(item, ReviewItem):
            return self.createIndex(item.parent.reviews.index(item), 0, item.parent)
        raise ValueError(f'Unknown {item}')

    def rowCount(self, index: QModelIndex | QPersistentModelIndex = QModelIndex()) -> int:
        parent: Item
        if not index.isValid():
            return len(self.root.threads)

        parent = index.internalPointer()

        if isinstance(parent, Root):
            return len(self.root.threads)
        if isinstance(parent, ThreadItem):
            return len(parent.reviews)
        return 0

    def columnCount(self, parent: QModelIndex | QPersistentModelIndex = QModelIndex()) -> int:
        return 1

    def data(self,
             index: QModelIndex | QPersistentModelIndex,
             role: int = Qt.ItemDataRole.DisplayRole) -> object:
        if self._pull_request is None:
            return None
        reviews: list[ReviewComment]  = self._pull_request._reviews
        review: ReviewComment = reviews[index.row()]

        item: Item = index.internalPointer()
        return item.data(role)

    def roleNames(self) -> dict[int, QByteArray]:
        return {
            Roles.Body: QByteArray(b'body'),
            Roles.CreatedAt: QByteArray(b'createdAt'),
            Roles.UpdatedAt: QByteArray(b'updatedAt'),
            Roles.Username: QByteArray(b'username'),
            Roles.AvatarUrl: QByteArray(b'avatarUrl'),
            Roles.Diff: QByteArray(b'diff'),
            Roles.Line: QByteArray(b'line'),
        }