-
Notifications
You must be signed in to change notification settings - Fork 58
/
MergeRequests.hs
373 lines (356 loc) · 15.3 KB
/
MergeRequests.hs
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -Wno-missing-export-lists #-}
{-# OPTIONS_GHC -Wno-missing-pattern-synonym-signatures -Wno-partial-fields #-}
{-# OPTIONS_GHC -Wno-unused-matches -Wno-unused-imports -Wno-orphans #-}
module Lentille.GitLab.MergeRequests where
import Data.Morpheus.Client
import Data.Text qualified as TE
import Data.Time.Clock
import Data.Time.Format (defaultTimeLocale, formatTime, parseTimeOrError)
import Data.Vector qualified as V
import Google.Protobuf.Timestamp qualified as T
import Lentille
import Lentille.GitLab.Adapter
import Lentille.GraphQL
import Monocle.Config qualified as Config
import Monocle.Entity
import Monocle.Prelude hiding (id, state)
import Monocle.Protob.Change
import Streaming.Prelude qualified as S
newtype NoteID = NoteID Text deriving (Show, Eq, FromJSON)
-- https://docs.gitlab.com/ee/api/graphql/reference/index.html#projectmergerequests
declareLocalTypesInline
glSchemaLocation
[raw|
query GetProjectMergeRequests ($project: ID!, $iids: [String!], $cursor: String) {
project(fullPath: $project) {
name
nameWithNamespace
mergeRequests (first: 100, after: $cursor, sort: UPDATED_DESC, iids: $iids) {
pageInfo {hasNextPage endCursor}
count
nodes {
id
iid
title
description
state
webUrl
commitCount
diffStatsSummary {
additions
deletions
fileCount
}
diffStats {
path
additions
deletions
}
commitsWithoutMergeCommits (first: 100) {
nodes {
sha
author {
username
}
authoredDate
title
}
}
author {
username
}
mergeUser {
username
}
sourceBranch
targetBranch
createdAt
updatedAt
mergedAt
mergeable
labels {
nodes {
title
}
}
assignees {
nodes {
username
}
}
notes {
nodes {
id
author {
username
}
createdAt
systemNoteIconName
}
}
draft
}
}
}
}
|]
fetchMergeRequest :: GraphEffects es => GraphClient -> Text -> Text -> Eff es (Either (FetchError GetProjectMergeRequests) GetProjectMergeRequests, [RequestLog])
fetchMergeRequest client project mrID =
fetchWithLog (doGraphRequest client) (GetProjectMergeRequestsArgs (ID project) (Just [mrID]) Nothing)
streamMergeRequests ::
GraphEffects es =>
GraphClient ->
-- A callback to get Ident ID from an alias
(Text -> Maybe Config.IdentUG) ->
UTCTime ->
Text ->
LentilleStream es Changes
streamMergeRequests client getIdentIdCb untilDate project =
streamDropBefore untilDate $ streamFetch client mkArgs defaultStreamFetchOptParams transformResponse'
where
mkArgs _ = GetProjectMergeRequestsArgs (ID project) Nothing
transformResponse' = transformResponse (host client) getIdentIdCb
transformResponse ::
Text ->
-- A callback to get Ident ID from an alias
(Text -> Maybe Config.IdentUG) ->
GetProjectMergeRequests ->
(PageInfo, Maybe RateLimit, GraphResponseResult, [(Change, [ChangeEvent])])
transformResponse host getIdentIdCB result =
case result of
GetProjectMergeRequests
( Just
( GetProjectMergeRequestsProject
shortName
fullName
( Just
( GetProjectMergeRequestsProjectMergeRequests
(GetProjectMergeRequestsProjectMergeRequestsPageInfo hasNextPage endCursor)
count
(Just nodes)
)
)
)
) ->
( PageInfo hasNextPage endCursor (Just count)
, Nothing
, NoErr
, extract shortName fullName <$> catMaybes nodes
)
_anyOtherResponse ->
( PageInfo False Nothing Nothing
, Nothing
, UnknownErr ["Unknown GetProjectMergeRequests response: " <> show result]
, []
)
where
toIdent' = toIdent host getIdentIdCB
toCommit' = toCommit host getIdentIdCB
extract :: Text -> Text -> GetProjectMergeRequestsProjectMergeRequestsNodes -> (Change, [ChangeEvent])
extract shortName fullName mr =
let change = getChange mr
comments = getComments mr
in ( change
, getChangeCreatedEvent change
<> getChangePushedEvent change
<> getChangeMergedEvent change
<> getChangeAbandonedEvent change
<> getChangeCommentedEvent change comments
<> getChangeReviewedEvent change comments
)
where
toDiffStatsSummary GetProjectMergeRequestsProjectMergeRequestsNodesDiffStatsSummary {..} = DiffStatsSummary {..}
toDiffStats GetProjectMergeRequestsProjectMergeRequestsNodesDiffStats {..} = DiffStats {..}
toMRCommit (GetProjectMergeRequestsProjectMergeRequestsNodesCommitsWithoutMergeCommitsNodes sha author' authoredDate ctitle) =
let cauthor = authorName <$> author' in MRCommit {..}
where
authorName GetProjectMergeRequestsProjectMergeRequestsNodesCommitsWithoutMergeCommitsNodesAuthor {..} = MRUserCore username
toCommitsNodes
(GetProjectMergeRequestsProjectMergeRequestsNodesCommitsWithoutMergeCommits nodes) = cleanMaybeMNodes nodes
toLabelsNodes
(GetProjectMergeRequestsProjectMergeRequestsNodesLabels nodes) = cleanMaybeMNodes nodes
toAssigneesNodes
(GetProjectMergeRequestsProjectMergeRequestsNodesAssignees nodes) = cleanMaybeMNodes nodes
getLabelTitle (GetProjectMergeRequestsProjectMergeRequestsNodesLabelsNodes title') = from title'
getAuthorUsername GetProjectMergeRequestsProjectMergeRequestsNodesAuthor {..} = username
getMergerUsername GetProjectMergeRequestsProjectMergeRequestsNodesMergeUser {..} = username
getAssigneesUsername GetProjectMergeRequestsProjectMergeRequestsNodesAssigneesNodes {..} = username
getChange :: GetProjectMergeRequestsProjectMergeRequestsNodes -> Change
getChange GetProjectMergeRequestsProjectMergeRequestsNodes {..} =
let changeId = (from . sanitizeID $ unpackID id)
changeNumber = getChangeNumber iid
changeChangeId = getChangeId fullName iid
changeTitle = from title
changeText = fromMTtoLT description
changeUrl = fromMTtoLT webUrl
changeCommitCount = (from $ fromMaybe 0 commitCount)
changeAdditions = (from $ getDSS (toDiffStatsSummary <$> diffStatsSummary) DSSAdditions)
changeDeletions = (from $ getDSS (toDiffStatsSummary <$> diffStatsSummary) DSSDeletions)
changeChangedFilesCount = (from $ getDSS (toDiffStatsSummary <$> diffStatsSummary) DSSFileCount)
changeChangedFiles = (fromList $ getChangedFile . toDiffStats <$> fromMaybe [] diffStats)
changeCommits = (fromList $ toCommit' . toMRCommit <$> maybe [] toCommitsNodes commitsWithoutMergeCommits)
changeRepositoryPrefix = from $ TE.replace ("/" <> shortName) "" $ stripSpaces fullName
changeRepositoryFullname = from $ stripSpaces fullName
changeRepositoryShortname = from shortName
changeAuthor = Just (maybe (ghostIdent host) (toIdent' . getAuthorUsername) author)
changeOptionalMergedBy =
( Just
. ChangeOptionalMergedByMergedBy
$ maybe (ghostIdent host) (toIdent' . getMergerUsername) mergeUser
)
changeOptionalMergedCommitSha = Nothing
changeBranch = from sourceBranch
changeTargetBranch = from targetBranch
changeCreatedAt = (Just $ timeToTimestamp Nothing createdAt)
changeOptionalMergedAt = (ChangeOptionalMergedAtMergedAt . timeToTimestamp Nothing <$> mergedAt)
changeUpdatedAt = (Just $ timeToTimestamp Nothing updatedAt)
-- No closedAt attribute for a MR then use updatedAt when the MR is closed state
changeOptionalClosedAt =
if isClosed $ toState state
then Just . ChangeOptionalClosedAtClosedAt $ timeToTimestamp Nothing updatedAt
else Nothing
changeState = toState state
changeOptionalDuration = case mergedAt of
Just merged_ts ->
Just
. ChangeOptionalDurationDuration
. from
$ diffTimeSec (timeToUTCTime Nothing merged_ts) (timeToUTCTime Nothing createdAt)
Nothing -> Nothing
-- TODO(fbo) Use the merge status : https://docs.gitlab.com/ee/api/graphql/reference/index.html#mergestatus
changeMergeable = (if mergeable then "MERGEABLE" else "CONFLICT")
changeLabels = (fromList $ getLabelTitle <$> maybe [] toLabelsNodes labels)
changeAssignees = (fromList $ toIdent' . getAssigneesUsername <$> maybe [] toAssigneesNodes assignees)
-- GitLab 13.12.X does not expose an approval attribute for mergeRequest
-- changeApprovals = (if approved then fromList ["APPROVED"] else fromList [])
changeApprovals = fromList []
changeDraft = draft
changeOptionalSelfMerged =
( ChangeOptionalSelfMergedSelfMerged
<$> ( (==)
<$> (getAuthorUsername <$> author)
<*> (getMergerUsername <$> mergeUser)
)
)
in Change {..}
getComments :: GetProjectMergeRequestsProjectMergeRequestsNodes -> [MRComment]
getComments GetProjectMergeRequestsProjectMergeRequestsNodes {..} =
toMRComment <$> maybe [] toNotesNodes (Just notes)
where
toNotesNodes (GetProjectMergeRequestsProjectMergeRequestsNodesNotes nodes) = cleanMaybeMNodes nodes
toMRComment :: GetProjectMergeRequestsProjectMergeRequestsNodesNotesNodes -> MRComment
toMRComment (GetProjectMergeRequestsProjectMergeRequestsNodesNotesNodes nId author' commentedAt ntypeM) =
let GetProjectMergeRequestsProjectMergeRequestsNodesNotesNodesAuthor author'' = author'
commentType = getCommentType ntypeM
NoteID noteIDT = nId
in MRComment
{ coId = sanitizeID noteIDT
, coAuthor = toIdent' author''
, coAuthoredAt = commentedAt
, coType = commentType
}
getCommentType = \case
Just "approval" -> CoApproval "Approved"
Just "unapproval" -> CoApproval "Unapproved"
Just _ -> CoOther
Nothing -> CoComment
getBaseEvent :: Change -> ChangeEvent
getBaseEvent Change {..} =
let changeEventOnAuthor = changeAuthor
changeEventOnCreatedAt = changeCreatedAt
changeEventRepositoryPrefix = changeRepositoryPrefix
changeEventRepositoryFullname = changeRepositoryFullname
changeEventRepositoryShortname = changeRepositoryShortname
changeEventBranch = changeBranch
changeEventTargetBranch = changeTargetBranch
changeEventNumber = changeNumber
changeEventChangeId = changeChangeId
changeEventUrl = changeUrl
changeEventChangedFiles = fmap toChangeFilePath changeChangedFiles
changeEventDraft = changeDraft
-- To be filled by caller function
changeEventCreatedAt = Nothing
changeEventAuthor = Nothing
changeEventType = Nothing
changeEventLabels = changeLabels
changeEventOptionalDuration = swapDuration <$> changeOptionalDuration
changeEventId = ""
changeEventOptionalMergedCommitSha = Nothing
in ChangeEvent {..}
where
toChangeFilePath ChangedFile {..} = ChangedFilePath changedFilePath
getChangeCreatedEvent :: Change -> [ChangeEvent]
getChangeCreatedEvent change =
[ (getBaseEvent change)
{ changeEventId = "ChangeCreatedEvent-" <> changeId change
, changeEventType = Just $ ChangeEventTypeChangeCreated ChangeCreatedEvent
, changeEventAuthor = changeAuthor change
, changeEventCreatedAt = changeCreatedAt change
}
]
getChangeMergedEvent :: Change -> [ChangeEvent]
getChangeMergedEvent change =
[ (getBaseEvent change)
{ changeEventId = "ChangeMergedEvent-" <> changeId change
, changeEventType = Just $ ChangeEventTypeChangeMerged ChangeMergedEvent
, changeEventAuthor = getMergedByIdent <$> changeOptionalMergedBy change
, changeEventCreatedAt = getMergedAt <$> changeOptionalMergedAt change
}
| isMerged $ changeState change
]
where
getMergedByIdent (ChangeOptionalMergedByMergedBy ident) = ident
getMergedAt (ChangeOptionalMergedAtMergedAt ts) = ts
getChangeAbandonedEvent :: Change -> [ChangeEvent]
getChangeAbandonedEvent change =
[ (getBaseEvent change)
{ changeEventId = "ChangeAbandonedEvent-" <> changeId change
, changeEventType = Just $ ChangeEventTypeChangeAbandoned ChangeAbandonedEvent
, -- GitLab Graph API does not report who closed a MR
changeEventAuthor = changeAuthor change
, changeEventCreatedAt = changeUpdatedAt change
}
| isClosed $ changeState change
]
getChangePushedEvent :: Change -> [ChangeEvent]
getChangePushedEvent change = toList $ mkPushEvent <$> changeCommits change
where
mkPushEvent Commit {..} =
(getBaseEvent change)
{ changeEventId = "ChangeCommitPushedEvent-" <> changeId change <> "-" <> commitSha
, changeEventType = Just $ ChangeEventTypeChangeCommitPushed ChangeCommitPushedEvent
, changeEventAuthor = commitAuthor
, changeEventCreatedAt = commitAuthoredAt
}
getChangeCommentedEvent :: Change -> [MRComment] -> [ChangeEvent]
getChangeCommentedEvent change comments =
toList $ mkCommentEvent <$> filter isComment comments
where
mkCommentEvent MRComment {..} =
(getBaseEvent change)
{ changeEventId = "ChangeCommentedEvent-" <> changeId change <> "-" <> from coId
, changeEventType = Just $ ChangeEventTypeChangeCommented ChangeCommentedEvent
, changeEventAuthor = Just coAuthor
, changeEventCreatedAt = Just $ timeToTimestamp Nothing coAuthoredAt
}
getChangeReviewedEvent :: Change -> [MRComment] -> [ChangeEvent]
getChangeReviewedEvent change comments =
toList $ mkCommentEvent <$> filter isApprovalComment comments
where
mkCommentEvent MRComment {..} =
let approval = case coType of
CoApproval approval' -> approval'
_ -> error "Runtime error"
in (getBaseEvent change)
{ changeEventId = "ChangeReviewedEvent-" <> changeId change <> "-" <> from coId
, changeEventType =
Just
. ChangeEventTypeChangeReviewed
. ChangeReviewedEvent
$ fromList [from approval]
, changeEventAuthor = Just coAuthor
, changeEventCreatedAt = Just $ timeToTimestamp Nothing coAuthoredAt
}