User: joe Date: 16 Nov 26 02:32 Revision: 48e225f7a1105c037c26d2d099bba77b6b0d30a4 Summary: Address review TeamCity URL: http://ci.mcdev.io:80/viewModification.html?tab=vcsModificationFiles&modId=10793&personal=false Index: buildSrc/src/main/kotlin/mcdev-core.gradle.kts =================================================================== --- buildSrc/src/main/kotlin/mcdev-core.gradle.kts (revision d9788239160383d194f5784f1dc2640ef14cc912) +++ buildSrc/src/main/kotlin/mcdev-core.gradle.kts (revision 48e225f7a1105c037c26d2d099bba77b6b0d30a4) @@ -193,7 +193,7 @@ tasks.runIde { maxHeapSize = "2G" jvmArgs("--add-exports=java.base/jdk.internal.vm=ALL-UNNAMED") - systemProperty("mcdev.annotater.upstream", "Earthcomputer/annotater") + systemProperty("mcdev.annotater.upstream", "Set the mcdev.annotater.upstream system property") } tasks.test { Index: src/main/kotlin/platform/fabric/annotater/AnnotaterVcs.kt =================================================================== --- src/main/kotlin/platform/fabric/annotater/AnnotaterVcs.kt (revision d9788239160383d194f5784f1dc2640ef14cc912) +++ src/main/kotlin/platform/fabric/annotater/AnnotaterVcs.kt (revision 48e225f7a1105c037c26d2d099bba77b6b0d30a4) @@ -117,7 +117,26 @@ interface AnnotaterPullRequests { enum class Action { CREATE, UPDATE } + enum class State { OPEN, CLOSED, MERGED } + /** + * @property state null until it has been looked up, or if it couldn't be + */ + data class PullRequest(val url: String, val state: State?) { + val number: String + get() = url.substringAfterLast('/') + + val closed: Boolean + get() = state == State.CLOSED || state == State.MERGED + } + + /** + * The pull request of the contribution checked out in [checkout], or null if it doesn't have one. This is cheap + * enough to call from any thread. The state is looked up in the background, updating the editor banners. + */ + fun currentPullRequest(checkout: AnnotaterCheckout): PullRequest? + + /** * Whether a pull request can be created or updated with the changes in [checkout], or null if there's nothing to * submit. This is cheap enough to call from any thread, so it may be null until the changes have been looked up. */ Index: src/main/kotlin/platform/fabric/annotater/github/AnnotaterGitHubPullRequests.kt =================================================================== --- src/main/kotlin/platform/fabric/annotater/github/AnnotaterGitHubPullRequests.kt (revision d9788239160383d194f5784f1dc2640ef14cc912) +++ src/main/kotlin/platform/fabric/annotater/github/AnnotaterGitHubPullRequests.kt (revision 48e225f7a1105c037c26d2d099bba77b6b0d30a4) @@ -39,25 +39,56 @@ import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.VcsException +import com.intellij.ui.EditorNotifications +import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.io.HttpRequests import java.io.IOException import java.net.HttpURLConnection +import java.net.URI import java.net.URLEncoder +import java.util.concurrent.ConcurrentHashMap import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.authentication.GHAccountsUtil import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.util.GHCompatibilityUtil class AnnotaterGitHubPullRequests : AnnotaterPullRequests { + /** + * The states of pull requests by URL, cached so that the editor banner can show them without blocking. + */ + private val states = ConcurrentHashMap() + + private val pendingStates = ConcurrentHashMap.newKeySet() + + private val stateExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor("Annotater pull request state", 1) + + private class CachedState(val state: AnnotaterPullRequests.State?, val time: Long) + override fun availableAction(checkout: AnnotaterCheckout): AnnotaterPullRequests.Action? { - val status = AnnotaterGitVcs.instance?.pushStatus(checkout)?.takeIf { it.hasUnpushedChanges } ?: return null - return if (status.pullRequestUrl != null) { + AnnotaterGitVcs.instance?.pushStatus(checkout)?.takeIf { it.hasUnpushedChanges } ?: return null + val pullRequest = currentPullRequest(checkout) + return if (pullRequest != null && !pullRequest.closed) { AnnotaterPullRequests.Action.UPDATE } else { AnnotaterPullRequests.Action.CREATE } } + override fun currentPullRequest(checkout: AnnotaterCheckout): AnnotaterPullRequests.PullRequest? { + val url = AnnotaterGitVcs.instance?.pushStatus(checkout)?.pullRequestUrl ?: return null + val cached = states[url] + if ((cached == null || System.currentTimeMillis() - cached.time > STATE_CACHE_MS) && pendingStates.add(url)) { + stateExecutor.execute { + try { + lookUpState(url) + } finally { + pendingStates.remove(url) + } + } + } + return AnnotaterPullRequests.PullRequest(url, cached?.state) + } + override fun submit(project: Project, checkout: AnnotaterCheckout) { val git = AnnotaterGitVcs.instance ?: return @@ -68,6 +99,7 @@ private var branch: String? = null private var existingTitle: String? = null private var existingUrl: String? = null + private var existingState: AnnotaterPullRequests.State? = null override fun run(indicator: ProgressIndicator) { changes = git.mappingFilesChangedSinceUpstream(project, checkout) @@ -76,6 +108,7 @@ branch = git.currentContribution(checkout)?.branch existingTitle = branch?.let { git.pullRequestTitle(project, checkout, it) } existingUrl = branch?.let { git.pullRequestUrl(project, checkout, it) } + existingState = existingUrl?.let { lookUpState(it) } } override fun onSuccess() { @@ -88,7 +121,17 @@ ) return } - showDialog(project, checkout, git, branch, changes, uncommittedChanges, existingTitle, existingUrl) + showDialog( + project, + checkout, + git, + branch, + changes, + uncommittedChanges, + existingTitle, + existingUrl, + existingState, + ) } override fun onThrowable(error: Throwable) { @@ -105,8 +148,12 @@ changes: List, uncommittedChanges: List, existingTitle: String?, - existingUrl: String?, + previousUrl: String?, + previousState: AnnotaterPullRequests.State?, ) { + // A closed pull request can't be updated, so a new one is opened instead + val previous = previousUrl?.let { AnnotaterPullRequests.PullRequest(it, previousState) } + val existingUrl = previous?.takeUnless { it.closed }?.url if (GHAccountsUtil.accounts.isEmpty()) { GHAccountsUtil.requestNewAccount(GithubServerPath.DEFAULT_SERVER, null, project) ?: return } @@ -129,6 +176,13 @@ uncommittedChanges, existingTitle, update = existingUrl != null, + notice = previousUrl?.let { url -> + when (previousState) { + AnnotaterPullRequests.State.MERGED -> MCDevBundle("fabric.annotater.pr.dialog.merged", url) + AnnotaterPullRequests.State.CLOSED -> MCDevBundle("fabric.annotater.pr.dialog.closed", url) + else -> MCDevBundle("fabric.annotater.pr.dialog.existing", url) + } + }, ) if (!dialog.showAndGet()) { return @@ -139,7 +193,7 @@ } val token = GHCompatibilityUtil.getOrRequestToken(account, project) ?: return - val request = PullRequest(dialog.prTitle, dialog.prDescription, dialog.commitMessage, branch, existingUrl) + val request = Submission(dialog.prTitle, dialog.prDescription, dialog.commitMessage, branch, existingUrl) val title = if (existingUrl != null) "fabric.annotater.pr.updating" else "fabric.annotater.pr.creating" object : Task.Backgroundable(project, MCDevBundle(title), false) { private var url: String? = null @@ -148,6 +202,7 @@ val url = submit(project, checkout, git, account, token, request, uncommittedChanges.isNotEmpty(), indicator) this.url = url + states[url] = CachedState(AnnotaterPullRequests.State.OPEN, System.currentTimeMillis()) git.setPullRequest(project, checkout, request.branch, url) if (existingUrl == null) { // Label the contribution with its pull request, for switching back to it later @@ -184,7 +239,7 @@ /** * @property existingUrl the URL of the pull request to update, or null to create one */ - private class PullRequest( + private class Submission( val title: String, val body: String, val commitMessage: String, @@ -202,7 +257,7 @@ git: AnnotaterGitVcs, account: GithubAccount, token: String, - request: PullRequest, + request: Submission, hasChanges: Boolean, indicator: ProgressIndicator, ): String { @@ -227,8 +282,13 @@ val cloneUrl = fork.get("clone_url").asString waitForFork(api, forkName, indicator) + // Name the fork's owner in the URL, so git credential helpers and the GitHub plugin authenticate the push as + // the selected account, rather than whichever account they'd use for github.com by default + val pushUrl = URI(cloneUrl).let { uri -> + URI(uri.scheme, forkOwner, uri.host, uri.port, uri.path, uri.query, uri.fragment).toString() + } indicator.text = MCDevBundle("fabric.annotater.pr.pushing") - git.push(project, checkout, cloneUrl, request.branch) + git.push(project, checkout, pushUrl, request.branch) if (request.existingUrl != null) { return request.existingUrl } @@ -257,6 +317,34 @@ } /** + * Looks up the state of the upstream pull request at [url] and caches it, updating the editor banners if it + * changed. Returns null if it can't be looked up, for example when offline or rate limited, in which case the + * previously cached state is kept. Pull requests are public, so this doesn't need an account. + */ + private fun lookUpState(url: String): AnnotaterPullRequests.State? { + val state = fetchState(url) + val old = states[url]?.state + states[url] = CachedState(state ?: old, System.currentTimeMillis()) + if (state != null && state != old) { + EditorNotifications.updateAll() + } + return state + } + + private fun fetchState(url: String): AnnotaterPullRequests.State? { + val number = url.substringAfterLast("/pull/", "").toIntOrNull() ?: return null + val pullRequest = runCatching { + GitHubApi(GithubServerPath.DEFAULT_SERVER.toApiUrl(), null) + .get("/repos/${AnnotaterGitVcs.upstreamRepository}/pulls/$number").asJsonObject + }.getOrNull() ?: return null + return when { + pullRequest.get("merged")?.asBoolean == true -> AnnotaterPullRequests.State.MERGED + pullRequest.get("state")?.asString == "open" -> AnnotaterPullRequests.State.OPEN + else -> AnnotaterPullRequests.State.CLOSED + } + } + + /** * Forks are created asynchronously, so wait until GitHub has finished creating it before pushing. */ private fun waitForFork(api: GitHubApi, forkName: String, indicator: ProgressIndicator) { @@ -271,13 +359,16 @@ private class GitHubApiException(val statusCode: Int, message: String) : IOException(message) - private class GitHubApi(private val baseUrl: String, private val token: String) { + /** + * @param token the account's token, or null to make unauthenticated requests + */ + private class GitHubApi(private val baseUrl: String, token: String?) { private val gson = Gson() - private val headers = mapOf( - "Authorization" to "Bearer $token", + private val headers = listOfNotNull( + token?.let { "Authorization" to "Bearer $it" }, "Accept" to "application/vnd.github+json", "X-GitHub-Api-Version" to "2022-11-28", - ) + ).toMap() fun post(path: String, body: JsonObject): JsonObject { return McdevHttp.post(baseUrl + path, "application/json", headers) @@ -342,6 +433,11 @@ companion object { private const val FORK_POLL_ATTEMPTS = 30 private const val FORK_POLL_DELAY_MS = 2000L + + /** + * How long a pull request's state is shown before it's looked up again. + */ + private const val STATE_CACHE_MS = 5 * 60 * 1000L private const val HTTP_UNPROCESSABLE_ENTITY = 422 } } Index: src/main/kotlin/platform/fabric/annotater/github/AnnotaterPullRequestDialog.kt =================================================================== --- src/main/kotlin/platform/fabric/annotater/github/AnnotaterPullRequestDialog.kt (revision d9788239160383d194f5784f1dc2640ef14cc912) +++ src/main/kotlin/platform/fabric/annotater/github/AnnotaterPullRequestDialog.kt (revision 48e225f7a1105c037c26d2d099bba77b6b0d30a4) @@ -42,6 +42,7 @@ private val uncommittedChanges: List, existingTitle: String?, private val update: Boolean, // existing PR or update? + private val notice: String?, // about the contribution's previous pull request, if it has one ) : DialogWrapper(project) { private val accountModel = CollectionComboBoxModel(accounts, defaultAccount ?: accounts.first()) @@ -65,6 +66,11 @@ } override fun createCenterPanel() = panel { + if (notice != null) { + row { + comment(notice) + } + } row(MCDevBundle("fabric.annotater.pr.dialog.account")) { comboBox(accountModel, SimpleListCellRenderer.create("") { it.name }) .align(AlignX.FILL) Index: src/main/kotlin/platform/fabric/annotater/javadoc/AnnotaterJavadocEditorNotificationProvider.kt =================================================================== --- src/main/kotlin/platform/fabric/annotater/javadoc/AnnotaterJavadocEditorNotificationProvider.kt (revision d9788239160383d194f5784f1dc2640ef14cc912) +++ src/main/kotlin/platform/fabric/annotater/javadoc/AnnotaterJavadocEditorNotificationProvider.kt (revision 48e225f7a1105c037c26d2d099bba77b6b0d30a4) @@ -25,6 +25,7 @@ import com.demonwav.mcdev.platform.fabric.annotater.AnnotaterPullRequests import com.demonwav.mcdev.platform.fabric.annotater.AnnotaterVcs import com.intellij.icons.AllIcons +import com.intellij.ide.BrowserUtil import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.project.Project @@ -45,12 +46,33 @@ val javadocEditor = AnnotaterJavadocInlineEditor.current(project)?.takeIf { it.checkout.root == checkout.root } val error = javadocEditor?.file?.error val pullRequests = AnnotaterPullRequests.instance + val pullRequest = pullRequests?.currentPullRequest(checkout) return Function { fileEditor -> - val status = - if (error != null) EditorNotificationPanel.Status.Error else EditorNotificationPanel.Status.Info + val status = when { + error != null -> EditorNotificationPanel.Status.Error + pullRequest != null -> EditorNotificationPanel.Status.Warning + else -> EditorNotificationPanel.Status.Info + } val panel = EditorNotificationPanel(fileEditor, status) - panel.text = error ?: MCDevBundle("fabric.annotater.banner", checkout.version, checkout.root) + panel.text = error ?: when { + pullRequest == null -> MCDevBundle("fabric.annotater.banner", checkout.version, checkout.root) + pullRequest.state == AnnotaterPullRequests.State.MERGED -> + MCDevBundle("fabric.annotater.banner.merged", pullRequest.number) + pullRequest.state == AnnotaterPullRequests.State.CLOSED -> + MCDevBundle("fabric.annotater.banner.closed", pullRequest.number) + else -> MCDevBundle("fabric.annotater.banner.pull_request", pullRequest.number, checkout.version) + } + if (pullRequest != null) { + panel.createActionLabel(MCDevBundle("fabric.annotater.banner.open_pull_request", pullRequest.number)) { + BrowserUtil.browse(pullRequest.url) + } + } + if (pullRequest?.closed == true) { + panel.createActionLabel(MCDevBundle("fabric.annotater.pr.start_new")) { + AnnotaterJavadocContributions.switchContribution(project, checkout, null) + } + } if (javadocEditor != null) { panel.createActionLabel(MCDevBundle("fabric.annotater.javadoc.finish")) { javadocEditor.finish() Index: src/main/resources/messages/MinecraftDevelopmentBundle.properties =================================================================== --- src/main/resources/messages/MinecraftDevelopmentBundle.properties (revision d9788239160383d194f5784f1dc2640ef14cc912) +++ src/main/resources/messages/MinecraftDevelopmentBundle.properties (revision 48e225f7a1105c037c26d2d099bba77b6b0d30a4) @@ -586,6 +586,10 @@ fabric.annotater.javadoc.edit=Edit Annotater Javadoc fabric.annotater.javadoc.open_failed=Failed to open annotater Javadoc fabric.annotater.banner=Annotater Javadocs for Minecraft {0} from {1}. Changes are saved automatically. +fabric.annotater.banner.pull_request=Changes are saved to the contribution for pull request #{0}, for Minecraft {1}. Start a new contribution for unrelated changes. +fabric.annotater.banner.closed=Pull request #{0} for this contribution was closed. It''s recommended to start a new contribution for new changes. +fabric.annotater.banner.merged=Pull request #{0} for this contribution was already merged. It''s recommended to start a new contribution for new changes. +fabric.annotater.banner.open_pull_request=Open #{0} fabric.annotater.javadoc.finish=Finish editing fabric.annotater.javadoc.save_failed=Failed to save annotater Javadoc fabric.annotater.javadoc.error.not_markdown=Annotater only supports Markdown Javadoc comments (///). Changes were not saved. @@ -615,6 +619,9 @@ fabric.annotater.pr.start_new=Start New Contribution fabric.annotater.pr.dialog.ok=Create Pull Request fabric.annotater.pr.dialog.update=Update Pull Request +fabric.annotater.pr.dialog.existing=The changes will be added to this contribution''s pull request, {0}. +fabric.annotater.pr.dialog.closed=This contribution''s pull request, {0}, was closed, so a new pull request will be opened. +fabric.annotater.pr.dialog.merged=This contribution''s pull request, {0}, was already merged, so a new pull request will be opened. If it was squash merged, the new pull request will repeat its changes, so consider starting a new contribution instead. fabric.annotater.pr.dialog.account=GitHub account\: fabric.annotater.pr.dialog.title=Title\: fabric.annotater.pr.dialog.description=Description\: