Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
gitlab: Add silent mention support for GitLab usernames.
The Dancef9b5b1d8bb06
diff --git a/starlight_help/src/content/docs/custom-profile-fields.mdx b/starlight_help/src/content/docs/custom-profile-fields.mdxindex c346f868fc6..896ec5b785f 100644--- a/starlight_help/src/content/docs/custom-profile-fields.mdx+++ b/starlight_help/src/content/docs/custom-profile-fields.mdx@@ -157,7 +157,8 @@ Choose the profile field type that's most appropriate for the requested informatGitLab, LinkedIn, etc.). You can[configure](#use-a-custom-profile-field-in--mention-suggestions) this field tobe used for [@-mention](/help/mention-a-user-or-group) suggestions. Some- integrations ([GitHub](/integrations/github)) use [silent+ integrations ([GitHub](/integrations/github),+ [GitLab](/integrations/gitlab)) use [silentmentions](/help/mention-a-user-or-group#silently-mention-a-user) to refer tousers if a matching external account is configured.* **Dropdown**: A dropdown with a list of predefined options (e.g.,diff --git a/zerver/webhooks/gitlab/doc.md b/zerver/webhooks/gitlab/doc.mdindex ee902b5827c..bfdb6da11f9 100644--- a/zerver/webhooks/gitlab/doc.md+++ b/zerver/webhooks/gitlab/doc.md@@ -2,6 +2,15 @@Receive GitLab notifications in Zulip!+!!! tip ""++ If you also configure a [custom profile+ field](/help/custom-profile-fields) for GitLab accounts, this+ integration will refer to GitLab users using [Zulip silent+ mentions](/help/mention-a-user-or-group#silently-mention-a-user),+ rather than their GitLab name.++{start_tabs}1. {!create-an-incoming-webhook.md!}diff --git a/zerver/webhooks/gitlab/tests.py b/zerver/webhooks/gitlab/tests.pyindex 41a732e05b3..39ebadbe9fe 100644--- a/zerver/webhooks/gitlab/tests.py+++ b/zerver/webhooks/gitlab/tests.py@@ -1,7 +1,9 @@from unittest.mock import MagicMock, patch+from zerver.actions.custom_profile_fields import try_add_realm_default_custom_profile_fieldfrom zerver.lib.test_classes import WebhookTestCasefrom zerver.lib.webhooks.git import COMMITS_LIMIT+from zerver.models.realms import get_realmclass GitlabHookTests(WebhookTestCase):@@ -695,13 +697,13 @@ A trivial change that should probably be ignored.def test_feature_flag_activate_event_message(self) -> None:expected_topic_name = "sample"- expected_message = "kolanuvarun739 activated the feature flag [sample-feature-flag](https://gitlab.com/kolanuvarun/sample/-/feature_flags)."+ expected_message = "Varun Kolanu activated the feature flag [sample-feature-flag](https://gitlab.com/kolanuvarun/sample/-/feature_flags)."self.check_webhook("feature_flag_hook__activated", expected_topic_name, expected_message)def test_feature_flag_deactivate_event_message(self) -> None:expected_topic_name = "sample"- expected_message = "kolanuvarun739 deactivated the feature flag [sample-feature-flag](https://gitlab.com/kolanuvarun/sample/-/feature_flags)."+ expected_message = "Varun Kolanu deactivated the feature flag [sample-feature-flag](https://gitlab.com/kolanuvarun/sample/-/feature_flags)."self.check_webhook("feature_flag_hook__deactivated", expected_topic_name, expected_message)@@ -843,3 +845,40 @@ A trivial change that should probably be ignored.expected_topic_name,expected_message,)++ def test_push_event_message_silent_mention(self) -> None:+ realm = get_realm("zulip")+ gitlab_field = try_add_realm_default_custom_profile_field(realm, "gitlab")+ hamlet = self.example_user("hamlet")+ self.set_user_custom_profile_data(+ hamlet, [{"id": gitlab_field.id, "value": "tomaszkolek0"}]+ )+ expected_topic_name = "my-awesome-project / tomek"+ expected_message = f"@_**{hamlet.full_name}|{hamlet.id}** [pushed](https://gitlab.com/tomaszkolek0/my-awesome-project/-/compare/5fcdd5551fc3085df79bece2c32b1400802ac407...eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9) 2 commits to branch tomek. Commits by Tomasz Kolek (2).\n\n* b ([66abd2da288](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/66abd2da28809ffa128ed0447965cf11d7f863a7))\n* c ([eb6ae1e591e](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9))"+ self.check_webhook("push_hook", expected_topic_name, expected_message)++ def test_update_issue_event_message_silent_mention(self) -> None:+ realm = get_realm("zulip")+ gitlab_field = try_add_realm_default_custom_profile_field(realm, "gitlab")+ hamlet = self.example_user("hamlet")+ self.set_user_custom_profile_data(+ hamlet, [{"id": gitlab_field.id, "value": "tomaszkolek0"}]+ )+ expected_topic_name = "my-awesome-project / issue #1 Issue title_new"+ expected_message = f"@_**{hamlet.full_name}|{hamlet.id}** updated [issue #1](https://gitlab.com/tomaszkolek0/my-awesome-project/issues/1)."+ self.check_webhook("issue_hook__issue_updated", expected_topic_name, expected_message)++ def test_update_issue_event_message_silent_mention_multiple_matches(self) -> None:+ realm = get_realm("zulip")+ gitlab_field = try_add_realm_default_custom_profile_field(realm, "gitlab")+ hamlet = self.example_user("hamlet")+ self.set_user_custom_profile_data(+ hamlet, [{"id": gitlab_field.id, "value": "tomaszkolek0"}]+ )+ cordelia = self.example_user("cordelia")+ self.set_user_custom_profile_data(+ cordelia, [{"id": gitlab_field.id, "value": "tomaszkolek0"}]+ )+ expected_topic_name = "my-awesome-project / issue #1 Issue title_new"+ expected_message = "Tomasz Kolek updated [issue #1](https://gitlab.com/tomaszkolek0/my-awesome-project/issues/1)."+ self.check_webhook("issue_hook__issue_updated", expected_topic_name, expected_message)diff --git a/zerver/webhooks/gitlab/view.py b/zerver/webhooks/gitlab/view.pyindex a58ef077c2c..fb820b4b16e 100644--- a/zerver/webhooks/gitlab/view.py+++ b/zerver/webhooks/gitlab/view.py@@ -7,7 +7,9 @@ from pydantic import Jsonfrom zerver.decorator import webhook_viewfrom zerver.lib.exceptions import UnsupportedWebhookEventTypeError+from zerver.lib.external_accounts import DEFAULT_EXTERNAL_ACCOUNTSfrom zerver.lib.markdown.fenced_code import get_unused_fence+from zerver.lib.mention import silent_mention_syntax_for_userfrom zerver.lib.partial import partialfrom zerver.lib.response import json_successfrom zerver.lib.typed_endpoint import JsonBodyPayload, typed_endpoint@@ -16,6 +18,7 @@ from zerver.lib.webhooks.common import (OptionalUserSpecifiedTopicStr,check_send_webhook_message,get_event_header,+ guess_zulip_user_from_external_account,)from zerver.lib.webhooks.git import (CONTENT_MESSAGE_TEMPLATE,@@ -31,7 +34,7 @@ from zerver.lib.webhooks.git import (get_remove_branch_event_message,is_branch_name_notifiable,)-from zerver.models import UserProfile+from zerver.models import Realm, UserProfileTOPIC_WITH_DESIGN_INFO_TEMPLATE = "{repo} / {type} {design_name}"DESIGN_COMMENT_MESSAGE_TEMPLATE = (@@ -55,16 +58,16 @@ def fixture_to_headers(fixture_name: str) -> dict[str, str]:return {"HTTP_X_GITLAB_EVENT": fixture_name.split("__", 1)[0].replace("_", " ").title()}-def get_push_event_body(payload: WildValue, include_title: bool) -> str:+def get_push_event_body(payload: WildValue, include_title: bool, realm: Realm) -> str:after = payload.get("after")if after:stringified_after = after.tame(check_string)if stringified_after == EMPTY_SHA:- return get_remove_branch_event_body(payload)- return get_normal_push_event_body(payload)+ return get_remove_branch_event_body(payload, realm)+ return get_normal_push_event_body(payload, realm)-def get_normal_push_event_body(payload: WildValue) -> str:+def get_normal_push_event_body(payload: WildValue, realm: Realm) -> str:compare_url = "{}/-/compare/{}...{}".format(get_project_homepage(payload),payload["before"].tame(check_string),@@ -82,29 +85,29 @@ def get_normal_push_event_body(payload: WildValue) -> str:]return get_push_commits_event_message(- get_user_name(payload),+ get_user_name(payload, realm),compare_url,get_branch_name(payload),commits,)-def get_remove_branch_event_body(payload: WildValue) -> str:+def get_remove_branch_event_body(payload: WildValue, realm: Realm) -> str:return get_remove_branch_event_message(- get_user_name(payload),+ get_user_name(payload, realm),get_branch_name(payload),)-def get_tag_push_event_body(payload: WildValue, include_title: bool) -> str:+def get_tag_push_event_body(payload: WildValue, include_title: bool, realm: Realm) -> str:return get_push_tag_event_message(- get_user_name(payload),+ get_user_name(payload, realm),get_tag_name(payload),action="pushed" if payload.get("checkout_sha") else "removed",)-def get_issue_created_event_body(payload: WildValue, include_title: bool) -> str:+def get_issue_created_event_body(payload: WildValue, include_title: bool, realm: Realm) -> str:description = payload["object_attributes"].get("description")# Filter out multiline hidden commentsif description:@@ -117,7 +120,7 @@ def get_issue_created_event_body(payload: WildValue, include_title: bool) -> strstringified_description = Nonereturn get_issue_event_message(- user_name=get_issue_user_name(payload),+ user_name=get_user_name(payload, realm),action="created",url=get_object_url(payload),number=payload["object_attributes"]["iid"].tame(check_int),@@ -127,9 +130,9 @@ def get_issue_created_event_body(payload: WildValue, include_title: bool) -> str)-def get_issue_event_body(action: str, payload: WildValue, include_title: bool) -> str:+def get_issue_event_body(action: str, payload: WildValue, include_title: bool, realm: Realm) -> str:return get_issue_event_message(- user_name=get_issue_user_name(payload),+ user_name=get_user_name(payload, realm),action=action,url=get_object_url(payload),number=payload["object_attributes"]["iid"].tame(check_int),@@ -137,22 +140,28 @@ def get_issue_event_body(action: str, payload: WildValue, include_title: bool) -)-def get_merge_request_updated_event_body(payload: WildValue, include_title: bool) -> str:+def get_merge_request_updated_event_body(+ payload: WildValue, include_title: bool, realm: Realm+) -> str:if payload["object_attributes"].get("oldrev"):return get_merge_request_event_body("added commit(s) to",payload,include_title=include_title,+ realm=realm,)return get_merge_request_open_or_updated_body("updated",payload,include_title=include_title,+ realm=realm,)-def get_merge_request_event_body(action: str, payload: WildValue, include_title: bool) -> str:+def get_merge_request_event_body(+ action: str, payload: WildValue, include_title: bool, realm: Realm+) -> str:pull_request = payload["object_attributes"]target_branch = Nonebase_branch = None@@ -161,7 +170,7 @@ def get_merge_request_event_body(action: str, payload: WildValue, include_title:base_branch = pull_request["target_branch"].tame(check_string)return get_pull_request_event_message(- user_name=get_issue_user_name(payload),+ user_name=get_user_name(payload, realm),action=action,url=pull_request["url"].tame(check_string),number=pull_request["iid"].tame(check_int),@@ -173,11 +182,14 @@ def get_merge_request_event_body(action: str, payload: WildValue, include_title:def get_merge_request_open_or_updated_body(- action: str, payload: WildValue, include_title: bool+ action: str,+ payload: WildValue,+ include_title: bool,+ realm: Realm,) -> str:pull_request = payload["object_attributes"]return get_pull_request_event_message(- user_name=get_issue_user_name(payload),+ user_name=get_user_name(payload, realm),action=action,url=pull_request["url"].tame(check_string),number=pull_request["iid"].tame(check_int),@@ -240,11 +252,11 @@ def parse_design_comment(comment: WildValue, repository_url: str) -> tuple[str,return comment_url, design_url, design_name-def get_commented_commit_event_body(payload: WildValue, include_title: bool) -> str:+def get_commented_commit_event_body(payload: WildValue, include_title: bool, realm: Realm) -> str:comment = payload["object_attributes"]action = "[commented]({})".format(comment["url"].tame(check_string))return get_commits_comment_action_message(- get_issue_user_name(payload),+ get_user_name(payload, realm),action,payload["commit"]["url"].tame(check_string),payload["commit"]["id"].tame(check_string),@@ -252,14 +264,16 @@ def get_commented_commit_event_body(payload: WildValue, include_title: bool) ->)-def get_commented_merge_request_event_body(payload: WildValue, include_title: bool) -> str:+def get_commented_merge_request_event_body(+ payload: WildValue, include_title: bool, realm: Realm+) -> str:comment = payload["object_attributes"]comment_url = comment["url"].tame(check_string)action = f"[commented]({comment_url}) on" if include_title else f"[commented]({comment_url})"url = payload["merge_request"]["url"].tame(check_string)return get_pull_request_event_message(- user_name=get_issue_user_name(payload),+ user_name=get_user_name(payload, realm),action=action,url=url,number=payload["merge_request"]["iid"].tame(check_int),@@ -270,14 +284,14 @@ def get_commented_merge_request_event_body(payload: WildValue, include_title: bo)-def get_commented_issue_event_body(payload: WildValue, include_title: bool) -> str:+def get_commented_issue_event_body(payload: WildValue, include_title: bool, realm: Realm) -> str:comment = payload["object_attributes"]comment_url = comment["url"].tame(check_string)action = f"[commented]({comment_url}) on" if include_title else f"[commented]({comment_url})"url = payload["issue"]["url"].tame(check_string)return get_pull_request_event_message(- user_name=get_issue_user_name(payload),+ user_name=get_user_name(payload, realm),action=action,url=url,number=payload["issue"]["iid"].tame(check_int),@@ -288,7 +302,7 @@ def get_commented_issue_event_body(payload: WildValue, include_title: bool) -> s)-def get_commented_design_event_body(payload: WildValue, include_title: bool) -> str:+def get_commented_design_event_body(payload: WildValue, include_title: bool, realm: Realm) -> str:comment = payload["object_attributes"]repository_url = payload["repository"]["homepage"].tame(check_string)@@ -305,7 +319,7 @@ def get_commented_design_event_body(payload: WildValue, include_title: bool) ->)return message_template.format(- user_name=get_issue_user_name(payload),+ user_name=get_user_name(payload, realm),action=action,design_name=design_name,design_url=design_url,@@ -313,7 +327,7 @@ def get_commented_design_event_body(payload: WildValue, include_title: bool) ->)-def get_commented_snippet_event_body(payload: WildValue, include_title: bool) -> str:+def get_commented_snippet_event_body(payload: WildValue, include_title: bool, realm: Realm) -> str:comment = payload["object_attributes"]comment_url = comment["url"].tame(check_string)action = f"[commented]({comment_url}) on" if include_title else f"[commented]({comment_url})"@@ -327,7 +341,7 @@ def get_commented_snippet_event_body(payload: WildValue, include_title: bool) ->)return get_pull_request_event_message(- user_name=get_issue_user_name(payload),+ user_name=get_user_name(payload, realm),action=action,url=url,number=payload["snippet"]["id"].tame(check_int),@@ -338,16 +352,20 @@ def get_commented_snippet_event_body(payload: WildValue, include_title: bool) ->)-def get_wiki_page_event_body(action: str, payload: WildValue, include_title: bool) -> str:+def get_wiki_page_event_body(+ action: str, payload: WildValue, include_title: bool, realm: Realm+) -> str:return '{} {} [wiki page "{}"]({}).'.format(- get_issue_user_name(payload),+ get_user_name(payload, realm),action,payload["object_attributes"]["title"].tame(check_string),payload["object_attributes"]["url"].tame(check_string),)-def get_build_hook_event_body(payload: WildValue, include_title: bool) -> str:+def get_build_hook_event_body(+ payload: WildValue, include_title: bool, realm: Realm | None = None+) -> str:build_status = payload["build_status"].tame(check_string)if build_status == "created":action = "was created"@@ -362,11 +380,13 @@ def get_build_hook_event_body(payload: WildValue, include_title: bool) -> str:)-def get_test_event_body(payload: WildValue, include_title: bool) -> str:+def get_test_event_body(payload: WildValue, include_title: bool, realm: Realm | None = None) -> str:return f"Webhook for **{get_repo_name(payload)}** has been configured successfully! :tada:"-def get_pipeline_event_body(payload: WildValue, include_title: bool) -> str:+def get_pipeline_event_body(+ payload: WildValue, include_title: bool, realm: Realm | None = None+) -> str:pipeline_status = payload["object_attributes"]["status"].tame(check_string)if pipeline_status == "pending":action = "was created"@@ -408,7 +428,9 @@ def get_pipeline_event_body(payload: WildValue, include_title: bool) -> str:)-def get_release_event_body(payload: WildValue, include_title: bool) -> str:+def get_release_event_body(+ payload: WildValue, include_title: bool, realm: Realm | None = None+) -> str:action = payload["action"].tame(check_string)name = payload["name"].tame(check_string)tag = payload["tag"].tame(check_string)@@ -433,13 +455,17 @@ def get_release_event_body(payload: WildValue, include_title: bool) -> str:return body-def get_feature_flag_event_body(payload: WildValue, include_title: bool) -> str:+def get_feature_flag_event_body(+ payload: WildValue,+ include_title: bool,+ realm: Realm,+) -> str:repo_url = payload["project"]["web_url"].tame(check_string)feature_flag = payload["object_attributes"]action = "activated" if feature_flag["active"] else "deactivated"return FEATURE_FLAG_MESSAGE_TEMPLATE.format(- user=payload["user"]["username"].tame(check_string),+ user=get_user_name(payload, realm),action=action,name=feature_flag["name"].tame(check_string),url=f"{repo_url}/-/feature_flags",@@ -459,7 +485,9 @@ def get_access_token_page_url(payload: WildValue) -> str:return f"{project_url}/-/settings/access_tokens"-def get_resource_access_token_expiry_event_body(payload: WildValue, include_title: bool) -> str:+def get_resource_access_token_expiry_event_body(+ payload: WildValue, include_title: bool, realm: Realm | None = None+) -> str:access_token = payload["object_attributes"]expiry_date = access_token["expires_at"].tame(check_string)formatted_date = datetime.fromisoformat(expiry_date).strftime("%b %d, %Y")@@ -471,10 +499,8 @@ def get_resource_access_token_expiry_event_body(payload: WildValue, include_titl)-def get_deployment_event_body(payload: WildValue, include_title: bool) -> str:- user_text = (- f"[{payload['user']['name'].tame(check_string)}]({payload['user_url'].tame(check_string)})"- )+def get_deployment_event_body(payload: WildValue, include_title: bool, realm: Realm) -> str:+ user_text = f"[{get_user_name(payload, realm)}]({payload['user_url'].tame(check_string)})"deployment_status = payload["status"].tame(check_string)deployable_url = payload.get("deployable_url", "").tame(check_string)@@ -553,7 +579,7 @@ def get_emoji_event_number_sign(type: str) -> str:return "" if type == "design" else "#"-def get_emoji_event_body(action: str, payload: WildValue, include_title: bool) -> str:+def get_emoji_event_body(action: str, payload: WildValue, include_title: bool, realm: Realm) -> str:transformed_action = {"award": "added", "revoke": "removed"}.get(action, "reacted")preposition = {"award": "to", "revoke": "from"}.get(action, "to")emoji = payload["object_attributes"]@@ -569,7 +595,7 @@ def get_emoji_event_body(action: str, payload: WildValue, include_title: bool) -suffix = f" {preposition} [{subtype}{target}]({url})"return EMOJI_MESSAGE_TEMPLATE.format(- user_name=get_issue_user_name(payload),+ user_name=get_user_name(payload, realm),action=transformed_action,emoji_text=emoji["name"].tame(check_string),suffix=suffix,@@ -591,12 +617,23 @@ def get_repo_name(payload: WildValue) -> str:return payload["group"]["group_name"].tame(check_string)-def get_user_name(payload: WildValue) -> str:- return payload["user_name"].tame(check_string)+def get_user_mention(realm: Realm, username: str, fallback_name: str) -> str:+ external_account_field_name = str(DEFAULT_EXTERNAL_ACCOUNTS["gitlab"].name)+ zulip_user = guess_zulip_user_from_external_account(+ realm, username, external_account_field_name, external_username_case_insensitive=True+ )++ if zulip_user is not None:+ return silent_mention_syntax_for_user(zulip_user)+ return fallback_name-def get_issue_user_name(payload: WildValue) -> str:- return payload["user"]["name"].tame(check_string)+def get_user_name(payload: WildValue, realm: Realm) -> str:+ # Push and tag events don't have a `user` section.+ user_data = payload["user"] if "user" in payload else payload+ username = user_data["username" if "user" in payload else "user_username"].tame(check_string)+ full_name = user_data["name" if "user" in payload else "user_name"].tame(check_string)+ return get_user_mention(realm, username, full_name)def get_project_homepage(payload: WildValue) -> str:@@ -635,7 +672,7 @@ def skip_previews(event: str) -> bool:class EventFunction(Protocol):- def __call__(self, payload: WildValue, include_title: bool) -> str: ...+ def __call__(self, payload: WildValue, include_title: bool, realm: Realm) -> str: ...EVENT_FUNCTION_MAPPER: dict[str, EventFunction] = {@@ -711,6 +748,7 @@ def api_gitlab_webhook(body = event_body_function(payload,include_title=user_specified_topic is not None,+ realm=user_profile.realm,)# Add a link to the project if a custom topic is set