1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 import java.net.HttpURLConnection
7 import java.nio.charset.StandardCharsets
9 class GitHubClient(token: String) {
11 private val tokenHeader = "Authorization" to "Bearer $token"
14 const val GITHUB_BASE_API = "https://api.github.com/repos"
17 fun createPullRequest(owner: String, repoName: String, bodyJson: String): Pair<Boolean, String> {
18 val url = "$GITHUB_BASE_API/$owner/$repoName/pulls"
20 return httpPOST(url, bodyJson, tokenHeader)
23 fun createIssue(owner: String, repoName: String, bodyJson: String): Pair<Boolean, String> {
24 val url = "$GITHUB_BASE_API/$owner/$repoName/issues"
26 return httpPOST(url, bodyJson, tokenHeader)
29 @Suppress("TooGenericExceptionCaught")
30 private fun httpPOST(urlString: String, json: String, vararg headers: Pair<String, String>): Pair<Boolean, String> {
31 val url = URL(urlString)
32 val http = url.openConnection() as HttpURLConnection
34 http.requestMethod = "POST"
36 http.setRequestProperty("Content-Type", "application/json; charset=UTF-8")
39 http.setRequestProperty(it.first, it.second)
42 http.outputStream.use { os ->
43 os.write(json.toByteArray(StandardCharsets.UTF_8))
46 var responseSuccessful = true
47 val textResponse = try {
48 http.inputStream.bufferedReader().readText()
49 } catch (e: Exception) {
50 responseSuccessful = false
51 http.errorStream.bufferedReader().readText()
53 return responseSuccessful to textResponse