Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,29 @@ The action accepts these inputs:

| Command | Description |
|---------|-------------|
| `/github map <github-login> @Wire user` | Register or replace an author mapping for this conversation; select the user with Wire’s mention picker. |
| `/github help` | List available commands and notification approaches. |
| `/github tokens` | Show or create the webhook secret and Actions token. |
| `/github webhook help` | Show repository webhook setup instructions. |
| `/github actions help` | Show the Actions endpoint, token usage, and reusable action example. |


Mappings are stored in Redis per conversation and preserve the registered login's capitalization.
Any conversation participant can register or replace a mapping. Use the same command again to update it.

| Notification | Who receives a native Wire mention |
|--------------|-------------------------------------|
| PR review request | The mapped requested reviewer. |
| PR review, PR inline comment, issue/PR conversation comment | Explicit `@github-login` tags in the body, excluding the reviewer/comment author. |
| Issue opened, reopened, closed | Explicit tags in the rendered title/body, excluding the issue author. |
| Custom Actions message | Explicit tags in `text`. |
| Other repository notifications | Nobody. |

Explicit tags require `@` and exact capitalization: mapping `octocat` matches `@octocat`,
but not `octocat` or `@Octocat`. Unmapped tags remain text. Email addresses and URL paths
are excluded. Team review requests do not create individual notifications.
Enable **Pull requests** in the repository webhook settings to receive review requests.

## Building & Running

To build or run the project, you can use the IDE Run configuration with environment variables.
Expand Down
7 changes: 7 additions & 0 deletions settings.gradle.kts
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
}
}

rootProject.name = "github"
75 changes: 75 additions & 0 deletions src/main/kotlin/com/wire/github/AuthorMentions.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package com.wire.github

import com.wire.github.response.model.GitHubResponse
import com.wire.github.util.TemplateHandler
import com.wire.sdk.model.QualifiedId
import com.wire.sdk.model.WireMessage

internal fun reviewRequestMentions(
event: String,
response: GitHubResponse,
conversationId: QualifiedId,
redisService: RedisService
): List<WireMessage.Mention> {
if (event != "pull_request" || response.action != "review_requested") return emptyList()
return response.requestedReviewer
?.login
?.let { login ->
redisService.getAuthorMapping(conversationId, login)?.let { userId ->
// The review-request template starts with the requested reviewer's @login.
listOf(WireMessage.Mention(userId = userId, offset = 0, length = login.length + 1))
}
}.orEmpty()
}

internal fun actionsMentions(
text: String,
conversationId: QualifiedId,
redisService: RedisService
): List<WireMessage.Mention> {
val mappings = redisService.getAuthorMappings(conversationId)
return textMentions(text, mappings)
}

private fun textMentions(
text: String,
mappings: Map<String, QualifiedId>
): List<WireMessage.Mention> {
if (mappings.isEmpty()) return emptyList()
val logins = mappings.keys.joinToString("|", transform = Regex::escape)
val pattern = Regex("(?<![\\w/@])@($logins)(?![\\w@/\\[-])")
return pattern
.findAll(text)
.map { match ->
WireMessage.Mention(
mappings.getValue(match.groupValues[1]),
match.range.first,
match.value.length
)
}.toList()
}

internal fun TemplateHandler.repositoryMentions(
event: String,
response: GitHubResponse,
text: String,
conversationId: QualifiedId,
redisService: RedisService
): List<WireMessage.Mention> {
val author = when (event) {
"pull_request_review" -> response.review?.user?.login ?: response.sender.login
"pull_request_review_comment", "issue_comment" -> response.comment?.user?.login
"issues" -> response.issue?.user?.login
else -> return reviewRequestMentions(event, response, conversationId, redisService)
}
val mappings = redisService.getAuthorMappings(conversationId)
val authorIds = mappings.filterKeys { it.equals(author, ignoreCase = true) }.values.toSet()
val others = mappings.filter { (login, userId) ->
!login.equals(author, ignoreCase = true) && userId !in authorIds
}
return mentionRanges(event, response).flatMap { range ->
textMentions(text.substring(range), others).map { mention ->
mention.copy(offset = mention.offset + range.first)
}
}
}
3 changes: 2 additions & 1 deletion src/main/kotlin/com/wire/github/EventsHandler.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ class EventsHandler : WireEventsHandlerSuspending() {
override suspend fun onTextMessageReceived(wireMessage: WireMessage.Text) {
val response = commandHandler.response(
command = wireMessage.text,
conversationId = wireMessage.conversationId
conversationId = wireMessage.conversationId,
mentions = wireMessage.mentions
) ?: return

logger.info(
Expand Down
45 changes: 43 additions & 2 deletions src/main/kotlin/com/wire/github/GitHubCommandHandler.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import com.wire.github.util.ENV_VAR_HOST
import com.wire.github.util.ActionsTokenGenerator
import com.wire.github.util.SessionIdentifierGenerator
import com.wire.sdk.model.QualifiedId
import com.wire.sdk.model.WireMessage

internal class GitHubCommandHandler(
private val redisService: RedisService,
Expand All @@ -15,15 +16,47 @@ internal class GitHubCommandHandler(
) {
fun response(
command: String,
conversationId: QualifiedId
conversationId: QualifiedId,
mentions: List<WireMessage.Mention> = emptyList()
): String? =
when (command.lowercase()) {
HELP_COMMAND -> trackedHelp(help())
WEBHOOK_HELP_COMMAND -> trackedHelp(webhookHelp(conversationId))
ACTIONS_HELP_COMMAND -> trackedHelp(actionsHelp(conversationId))
else -> null
else -> registerMapping(command, conversationId, mentions)
}

private fun registerMapping(
command: String,
conversationId: QualifiedId,
mentions: List<WireMessage.Mention>
): String? {
val parts = command.split(Regex("\\s+"), limit = 4)
if (!parts.first().equals("/github", ignoreCase = true) ||
!parts.getOrNull(1).equals("map", ignoreCase = true)
) {
return null
}
val match = MAPPING_COMMAND.matchEntire(command)
val mention = mentions.singleOrNull()
val login = match
?.groupValues
?.get(1)
.orEmpty()
.removePrefix("@")
val target = match?.groups?.get(2)
val selectedUser = mention?.takeIf {
it.offset == target?.range?.first && it.length == target.value.length
}
return if (!GITHUB_LOGIN.matches(login) || selectedUser == null) {
"Usage: `/github map <github-login> @Wire user` " +
"(select one user from Wire's mention picker)."
} else {
redisService.setAuthorMapping(conversationId, login, selectedUser.userId)
"Mapped GitHub @$login to the selected Wire user in this conversation."
}
}

fun help(): String =
"GitHub App supports repository webhooks and workflow-authored Actions notifications.\n\n" +
HELP_COMMANDS
Expand Down Expand Up @@ -76,11 +109,19 @@ internal class GitHubCommandHandler(
get() = host.trimEnd('/')

companion object {
private val MAPPING_COMMAND = Regex(
"/github\\s+map\\s+([^\\s]+)\\s+(.+)",
RegexOption.IGNORE_CASE
)
private val GITHUB_LOGIN = Regex(
"[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,37}[a-zA-Z0-9])?(?:\\[bot\\])?"
)
const val HELP_COMMAND = "/github help"
const val WEBHOOK_HELP_COMMAND = "/github webhook help"
const val ACTIONS_HELP_COMMAND = "/github actions help"
const val HELP_COMMANDS =
"Available commands:\n" +
"- `/github map <github-login> @Wire user` - map a PR reviewer\n" +
"- `$WEBHOOK_HELP_COMMAND` - configure GitHub repository webhooks\n" +
"- `$ACTIONS_HELP_COMMAND` - send custom messages from GitHub Actions\n" +
"- `$HELP_COMMAND` - Show this help message"
Expand Down
28 changes: 28 additions & 0 deletions src/main/kotlin/com/wire/github/RedisService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,37 @@ import java.util.UUID
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

@Suppress("TooManyFunctions")
class RedisService(
private val storage: RedisCommands<String, String>
) {
fun getAuthorMapping(
conversationId: QualifiedId,
login: String
): QualifiedId? =
storage
.hget(
"${conversationId.toWebhookStorageKey()}:authors",
login
)?.let(QualifiedId::fromFullString)

fun getAuthorMappings(conversationId: QualifiedId): Map<String, QualifiedId> =
storage
.hgetall("${conversationId.toWebhookStorageKey()}:authors")
.mapValues { (_, userId) -> QualifiedId.fromFullString(userId) }

fun setAuthorMapping(
conversationId: QualifiedId,
login: String,
userId: QualifiedId
) {
storage.hset(
"${conversationId.toWebhookStorageKey()}:authors",
login,
userId.toFullString()
)
}

fun getWebhookSecret(conversationId: QualifiedId): String? =
storage.get(conversationId.toWebhookStorageKey())

Expand Down
12 changes: 10 additions & 2 deletions src/main/kotlin/com/wire/github/Routing.kt
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,14 @@ fun Application.configureRouting() {
id = UUID.fromString(conversationId),
domain = conversationDomain
),
text = messageTemplate
text = messageTemplate,
mentions = templateHandler.repositoryMentions(
event,
response,
messageTemplate,
QualifiedId(UUID.fromString(conversationId), conversationDomain),
redisService
)
)
)
usageMetrics.onNotificationSent(event = event)
Expand Down Expand Up @@ -212,7 +219,8 @@ private fun Route.configureActionsRoute(
wireAppSdk.getApplicationManager().sendMessage(
message = WireMessage.Text.create(
conversationId = qualifiedConversationId,
text = request.text
text = request.text,
mentions = actionsMentions(request.text, qualifiedConversationId, redisService)
)
)
call.response.status(HttpStatusCode.OK)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ data class GitHubResponse(
val action: String? = null,
@SerialName("pull_request")
val pullRequest: PullRequest? = null,
@SerialName("requested_reviewer")
val requestedReviewer: User? = null,
val comment: Comment? = null,
val issue: Issue? = null,
val commits: List<Commit> = emptyList(),
Expand Down
44 changes: 44 additions & 0 deletions src/main/kotlin/com/wire/github/util/TemplateHandler.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import com.wire.github.response.model.GitHubResponse
import java.io.PrintWriter
import java.io.StringWriter
import java.util.Locale
import java.util.UUID
import org.slf4j.LoggerFactory

class TemplateHandler {
Expand All @@ -33,6 +34,49 @@ class TemplateHandler {
null
}

fun mentionRanges(
event: String,
response: GitHubResponse
): List<IntRange> {
val content = mutableMapOf<String, String>()

fun mark(value: String?): String? =
value?.let {
val marker = UUID.randomUUID().toString()
content[marker] = it
marker
}
val marked = when (event) {
"pull_request_review" -> response.copy(
review = response.review?.let { it.copy(body = mark(it.body)) }
)
"pull_request_review_comment", "issue_comment" -> response.copy(
comment = response.comment?.let { it.copy(body = mark(it.body)) }
)
"issues" -> response.copy(
issue = response.issue?.let {
it.copy(
title = mark(it.title)!!,
body = mark(it.body)
)
}
)
else -> return emptyList()
}
val rendered = handleEvent(event, marked).orEmpty()
// Placeholders distinguish user-authored fields from identical text in headers.
var adjustment = 0
return content.entries
.mapNotNull { (marker, value) ->
rendered.indexOf(marker).takeIf { it >= 0 }?.let { Triple(it, marker, value) }
}.sortedBy { it.first }
.map { (offset, marker, value) ->
val start = offset + adjustment
adjustment += value.length - marker.length
start until start + value.length
}
}

private fun compileTemplate(
event: String,
action: String?
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{{#requestedReviewer}}@{{requestedReviewer.login}}, your review was requested by **{{sender.login}}**.
**[{{repository.fullName}}]** PR #{{pullRequest.number}}: **{{{pullRequest.title}}}**
{{pullRequest.htmlUrl}}
{{/requestedReviewer}}
Loading