This repository has been archived by the owner on Apr 22, 2020. It is now read-only.
/
GitHubOps.scala
406 lines (345 loc) · 14.5 KB
/
GitHubOps.scala
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/*
* Copyright 2017-2020 47 Degrees, LLC. <http://www.47deg.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sbtorgpolicies.github
import java.io.File
import cats.data.{EitherT, NonEmptyList}
import cats.effect.{ConcurrentEffect, IO, Sync, Timer}
import cats.implicits._
import com.github.marklister.base64.Base64._
import github4s.Github
import github4s.GithubResponses._
import github4s.domain._
import sbtorgpolicies.exceptions.{GitHubException, IOException, OrgPolicyException}
import sbtorgpolicies.github.config._
import sbtorgpolicies.io.{FileReader, IO => FIO}
import scala.concurrent.ExecutionContext
import scala.concurrent.duration._
class GitHubOpsIO(
owner: String,
repo: String,
accessToken: Option[String],
fileReader: FileReader = FileReader
)(implicit ec: ExecutionContext, ce: ConcurrentEffect[IO], t: Timer[IO])
extends GitHubOps[IO](owner, repo, accessToken, fileReader)
class GitHubOps[F[_]: ConcurrentEffect: Timer](
owner: String,
repo: String,
accessToken: Option[String],
fileReader: FileReader = FileReader
)(implicit ec: ExecutionContext) {
val gh: Github[F] = Github[F](accessToken)
val headers: Map[String, String] = Map("user-agent" -> "sbt-org-policies")
def fetchContributors: EitherT[F, GitHubException, List[User]] = {
def fetchUserList: EitherT[F, GitHubException, List[User]] =
run(gh.repos.listContributors(owner, repo, headers = headers))
def fetchUserDetail(user: User): EitherT[F, GitHubException, User] =
run(gh.users.get(user.login, headers = headers))
for {
response <- fetchUserList
detailedResponse <- response.traverse(fetchUserDetail)
} yield detailedResponse
}
def commitFiles(
baseDir: File,
branch: String,
message: String,
files: List[File]
): EitherT[F, OrgPolicyException, Option[Ref]] = {
def relativePath(file: File): F[String] =
Sync[F].delay(FIO.relativize(baseDir, file).getOrElse(file.getName))
def readFileContents: EitherT[F, IOException, List[(String, String)]] =
files.traverse { file =>
for {
path <- EitherT.right(Sync[F].delay(file.getAbsolutePath()))
content <- EitherT(Sync[F].delay(fileReader.getFileContent(path)))
relativePath <- EitherT.right(relativePath(file))
} yield (relativePath, content)
}
readFileContents
.leftMap[OrgPolicyException](identity)
.flatMap { filesAndContents =>
commitFilesAndContents(branch, message, filesAndContents)
.leftMap[OrgPolicyException](identity)
}
}
def commitFilesAndContents(
branch: String,
message: String,
filesAndContents: List[(String, String)]
): EitherT[F, GitHubException, Option[Ref]] = {
def fetchBaseTreeSha(commitSha: String): EitherT[F, GitHubException, RefCommit] =
run(gh.gitData.getCommit(owner, repo, commitSha))
def fetchFilesContents(
commitSha: String
): EitherT[F, GitHubException, List[(String, Option[String])]] = {
def fetchFileContents(
path: String,
commitSha: String
): EitherT[F, GitHubException, (String, Option[String])] = {
runOption(
gh.repos.getContents(owner = owner, repo = repo, path = path, ref = Some(commitSha))
).map(res => path -> res.flatMap(_.head.content))
}
filesAndContents.map(_._1).traverse(fetchFileContents(_, commitSha))
}
def filterNonChangedFiles(remote: List[(String, Option[String])]): List[(String, String)] = {
val remoteMap = remote.collect {
case (path, Some(c)) => path -> c
}.toMap
filesAndContents.filterNot {
case (path, content) =>
remoteMap.get(path).exists { remoteContent =>
remoteContent.trim.replaceAll("\n", "") == content.getBytes.toBase64.trim
}
}
}
def createTree(
baseTreeSha: String,
filteredFilesContent: List[(String, String)]
): EitherT[F, GitHubException, TreeResult] = {
val treeData: List[TreeDataBlob] = filteredFilesContent.map {
case (path, content) => TreeDataBlob(path, blobMode, blobType, content)
}
run(gh.gitData.createTree(owner, repo, Some(baseTreeSha), treeData))
}
def createCommit(
treeSha: String,
baseCommitSha: String
): EitherT[F, GitHubException, RefCommit] =
run(gh.gitData.createCommit(owner, repo, message, treeSha, List(baseCommitSha), None))
def commitFilesIfChanged(
baseTreeSha: String,
parentCommitSha: String,
filteredFilesContent: List[(String, String)]
): EitherT[F, GitHubException, Option[Ref]] =
filteredFilesContent match {
case Nil =>
EitherT.rightT(none[Ref])
case list =>
for {
ghResultTree <- createTree(baseTreeSha, list)
ghResultCommit <- createCommit(ghResultTree.sha, parentCommitSha)
ghResultUpdate <- updateHead(branch, ghResultCommit.sha)
} yield Option(ghResultUpdate)
}
for {
gHResultParentCommit <- fetchHeadCommit(branch)
parentCommitSha = gHResultParentCommit.`object`.sha
gHResultBaseTree <- fetchBaseTreeSha(parentCommitSha)
baseTreeSha = gHResultBaseTree.tree.sha
ghResultFilesContent <- fetchFilesContents(parentCommitSha)
ghResultUpdate <- commitFilesIfChanged(
baseTreeSha,
parentCommitSha,
filterNonChangedFiles(ghResultFilesContent)
)
} yield ghResultUpdate
}
def commitDir(branch: String, message: String, dir: File): EitherT[F, OrgPolicyException, Ref] =
EitherT(Sync[F].delay(fileReader.fetchDirsRecursively(List(dir)))).flatMap {
case Nil => EitherT.leftT(IOException(s"Nothing to commit in dir ${dir.getAbsolutePath}"))
case h :: t =>
commitDir(branch, message, dir, NonEmptyList(h, t))
.leftMap[OrgPolicyException](identity)
}
def commitDir(
branch: String,
message: String,
baseDir: File,
dirList: NonEmptyList[File],
blobConfig: BlobConfig = defaultBlobConfig
): EitherT[F, GitHubException, Ref] = {
def updateCommitDirH(dir: File, sha: Option[String]): EitherT[F, GitHubException, RefCommit] =
updateCommitDir(branch, message, baseDir, dir, blobConfig, sha)
val processAllFiles: EitherT[F, GitHubException, RefCommit] =
dirList.reduceLeftM(dirHead => updateCommitDirH(dirHead, None)) { (commit, dir) =>
updateCommitDirH(dir, Some(commit.sha))
}
for {
lastCommit <- processAllFiles
headRef <- updateHead(branch, lastCommit.sha)
} yield headRef
}
private[this] def updateCommitDir(
branch: String,
message: String,
baseDir: File,
dirToCommit: File,
blobConfig: BlobConfig,
commitSha: Option[String]
): EitherT[F, GitHubException, RefCommit] = {
def fetchBaseTreeSha: EitherT[F, GitHubException, Option[RefCommit]] =
commitSha
.map { sha =>
run(gh.gitData.getCommit(owner, repo, sha)).map(Option.apply)
}
.getOrElse(EitherT.rightT(none[RefCommit]))
def getAllFiles: List[File] = Option(dirToCommit.listFiles()).toList.flatten.filter(_.isFile)
def createTreeDataList(files: List[File]): EitherT[F, GitHubException, List[TreeData]] = {
def readFileAsGithub4sResponse(file: File): EitherT[F, GitHubException, Array[Byte]] =
EitherT {
Sync[F].delay(fileReader.getFileBytes(file).leftMap(e => GitHubException(e.getMessage)))
}
def path(file: File): EitherT[F, GitHubException, String] =
EitherT.fromOptionF(
Sync[F].delay(FIO.relativize(baseDir, file)),
GitHubException(s"Can't determine path for ${file.getAbsolutePath}")
)
def createTreeDataSha(
filePath: String,
array: Array[Byte]
): EitherT[F, GitHubException, TreeData] =
for {
gh <- EitherT.right(ghWithRateLimit)
res <- run(gh.gitData.createBlob(owner, repo, array.toBase64, Some("base64")))
.map(refInfo => TreeDataSha(filePath, blobMode, blobType, refInfo.sha))
} yield res
def createTreeDataBlob(
filePath: String,
array: Array[Byte]
): EitherT[F, GitHubException, TreeData] =
EitherT.rightT(TreeDataBlob(filePath, blobMode, blobType, new String(array)): TreeData)
def createTreeData(
file: File,
filePath: String,
array: Array[Byte]
): EitherT[F, GitHubException, TreeData] =
if (blobConfig.acceptedExtensions.exists(s => file.getName.toLowerCase.endsWith(s)) &&
array.length < blobConfig.maximumSize) {
createTreeDataBlob(filePath, array)
} else {
createTreeDataSha(filePath, array)
}
def processFile(file: File): EitherT[F, GitHubException, TreeData] =
for {
filePath <- path(file)
array <- readFileAsGithub4sResponse(file)
treeData <- createTreeData(file, filePath, array)
} yield treeData
files.traverse(processFile)
}
def createTree(
baseTreeSha: Option[String],
treeData: List[TreeData]
): EitherT[F, GitHubException, TreeResult] =
for {
gh <- EitherT.right(ghWithRateLimit)
res <- run(gh.gitData.createTree(owner, repo, baseTreeSha, treeData))
} yield res
def createCommit(
treeSha: String,
parentCommit: String
): EitherT[F, GitHubException, RefCommit] =
for {
gh <- EitherT.right(ghWithRateLimit)
res <- run(
gh.gitData.createCommit(owner, repo, message, treeSha, List(parentCommit), author = None)
)
} yield res
def parentCommitSha: EitherT[F, GitHubException, String] = commitSha match {
case Some(sha) => EitherT.rightT(sha)
case None => fetchHeadCommit(branch).map(_.`object`.sha)
}
for {
parentCommit <- parentCommitSha
baseTree <- fetchBaseTreeSha
treeDataList <- createTreeDataList(getAllFiles)
treeResult <- createTree(baseTree.map(_.tree.sha), treeDataList)
refCommit <- createCommit(treeResult.sha, parentCommit)
} yield refCommit
}
def fetchReference(ref: String): EitherT[F, GitHubException, NonEmptyList[Ref]] =
run(gh.gitData.getReference(owner, repo, ref))
def createTagRelease(
branch: String,
tag: String,
message: String,
releaseDescription: String
): EitherT[F, GitHubException, Release] = {
def createTag(obj: RefObject): EitherT[F, GitHubException, Tag] =
run(gh.gitData.createTag(owner, repo, tag, message, obj.sha, obj.`type`))
def createTagReference(commitSha: String): EitherT[F, GitHubException, Ref] =
run(gh.gitData.createReference(owner, repo, s"refs/tags/$tag", commitSha))
def createRelease: EitherT[F, GitHubException, Release] =
run(gh.repos.createRelease(owner, repo, tag, tag, releaseDescription))
for {
headCommit <- fetchHeadCommit(branch)
tagResponse <- createTag(headCommit.`object`)
_ <- createTagReference(tagResponse.sha)
release <- createRelease
} yield release
}
def latestPullRequests(
branch: String,
inPath: String,
message: String
): EitherT[F, GitHubException, List[PullRequest]] = {
def fetchLastCommit: EitherT[F, GitHubException, Option[Commit]] = {
def findCommit(list: List[Commit]): Option[Commit] =
list.sortBy(_.date)(Ordering[String].reverse).find(_.message.contains(message))
run(gh.repos.listCommits(owner = owner, repo = repo, path = Some(inPath)))
.map(findCommit)
}
def fetchPullRequests(
maybeDate: Option[String]
): EitherT[F, GitHubException, List[PullRequest]] = {
def orderAndFilter(list: List[PullRequest]): List[PullRequest] = {
val date = maybeDate.getOrElse("")
list.mapFilter(pr => pr.merged_at.filter(_ > date).as(pr)).reverse
}
val filters =
List(PRFilterClosed, PRFilterBase(branch), PRFilterSortUpdated, PRFilterOrderDesc)
run(gh.pullRequests.listPullRequests(owner, repo, filters)).map(orderAndFilter)
}
for {
maybeCommit <- fetchLastCommit
list <- fetchPullRequests(maybeCommit.map(_.date))
} yield list
}
def fetchHeadCommit(branch: String): EitherT[F, GitHubException, Ref] = {
def findReference(refs: NonEmptyList[Ref]): EitherT[F, GitHubException, Ref] =
refs.find(_.ref == s"refs/heads/$branch") match {
case Some(ref) => EitherT.rightT(ref)
case None =>
EitherT.leftT(
GitHubException(s"GitHub returned an error: Branch $branch not found", None)
)
}
run(gh.gitData.getReference(owner, repo, s"heads/$branch")).flatMap(findReference)
}
def updateHead(branch: String, commitSha: String): EitherT[F, GitHubException, Ref] =
run(gh.gitData.updateReference(owner, repo, s"heads/$branch", commitSha, force = false))
def run[A](f: F[GHResponse[A]]): EitherT[F, GitHubException, A] = EitherT(
Sync[F].attempt(f).map {
case Right(GHResponse(Right(r), _, _)) => Right(r)
case Right(GHResponse(Left(e), _, _)) =>
Left(GitHubException(s"GitHub returned an error: ${e.getMessage}", Some(e)))
case Left(e) => Left(GitHubException("Error making request to GitHub", Some(e)))
}
)
def runOption[A](f: F[GHResponse[A]]): EitherT[F, GitHubException, Option[A]] = EitherT(
Sync[F].attempt(f).map {
case Right(GHResponse(Right(r), _, _)) => r.some.asRight[GitHubException]
case Right(GHResponse(Left(e), 404, _)) => none[A].asRight[GitHubException]
case Right(GHResponse(Left(e), _, _)) =>
Left(GitHubException(s"GitHub returned an error: ${e.getMessage}", Some(e)))
case Left(e) => Left(GitHubException("Error making request to GitHub", Some(e)))
}
)
// Due to GitHub abuse rate limits, we should wait 1 sec between each request
// https://developer.github.com/guides/best-practices-for-integrators/#dealing-with-abuse-rate-limits
def ghWithRateLimit: F[Github[F]] = Timer[F].sleep(1.second).as(gh)
}