##// END OF EJS Templates
deps: bumped debug deps
deps: bumped debug deps

File last commit:

r5623:2f80d511 default
r5634:322d43be default
Show More
repo.py
427 lines | 14.1 KiB | text/x-python | PythonLexer
core: updated copyright to 2024
r5608 # Copyright (C) 2016-2024 RhodeCode GmbH
dan
events: add event system for RepoEvents
r375 #
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License, version 3
# (only), as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# This program is dual-licensed. If you wish to learn more about the
# RhodeCode Enterprise Edition, including its added features, Support services,
# and proprietary license terms, please see https://rhodecode.com/licenses/
webhook: enable support of extra repo variables as replacement in template url.
r1761 import collections
dan
integrations: add integration support...
r411 import logging
integrations: parse pushed tags, and lightweight tags for git....
r2422 import datetime
dan
events: add serialization .to_dict() to events based on marshmallow
r379
dan
integrations: add integration support...
r411 from rhodecode.translation import lazy_ugettext
core: revamp of automation/scheduler/artifacts EE functionality
r5137 from rhodecode.model.db import User, Repository
events: use a distinction between RhodeCodeEvent which is a base class and it used by all events, and...
r2921 from rhodecode.events.base import RhodeCodeIntegrationEvent
dan
events: change target to source repo for pull request events...
r514 from rhodecode.lib.vcs.exceptions import CommitDoesNotExistError
dan
events: add serialization .to_dict() to events based on marshmallow
r379
Martin Bornhold
logging: Use __name__ when requesting a logger
r504 log = logging.getLogger(__name__)
dan
events: add event system for RepoEvents
r375
events: fixed missing construcors on user based events.
r1422
events: re-organizate events handling....
r1789 def _commits_as_dict(event, commit_ids, repos):
dan
events: change target to source repo for pull request events...
r514 """
Helper function to serialize commit_ids
events: re-organizate events handling....
r1789 :param event: class calling this method
dan
events: change target to source repo for pull request events...
r514 :param commit_ids: commits to get
core: revamp of automation/scheduler/artifacts EE functionality
r5137 :param repos: a list of repos to check
dan
events: change target to source repo for pull request events...
r514 """
from rhodecode.lib.utils2 import extract_mentioned_users
feat(events): added context into events so we can track additional context of calling it
r5623 from rhodecode.lib.helpers import urlify_commit_message, process_patterns, chop_at_smart
events: expose permalink urls for different set of object....
r1788 from rhodecode.model.repo import RepoModel
dan
events: change target to source repo for pull request events...
r514
if not repos:
feat(events): added context into events so we can track additional context of calling it
r5623 raise Exception("no repo defined")
dan
events: change target to source repo for pull request events...
r514
if not isinstance(repos, (tuple, list)):
repos = [repos]
if not commit_ids:
return []
dan
events: send pushed commit ids in order
r782 needed_commits = list(commit_ids)
dan
events: change target to source repo for pull request events...
r514
commits = []
reviewers = []
for repo in repos:
if not needed_commits:
events: expose permalink urls for different set of object....
r1788 return commits # return early if we have the commits we need
dan
events: change target to source repo for pull request events...
r514
vcs_repo = repo.scm_instance(cache=False)
integrations: parse pushed tags, and lightweight tags for git....
r2422
dan
events: change target to source repo for pull request events...
r514 try:
dan
events: fix bug with _commits_as_dict which was returning only...
r795 # use copy of needed_commits since we modify it while iterating
for commit_id in list(needed_commits):
feat(events): added context into events so we can track additional context of calling it
r5623 if commit_id.startswith("tag=>"):
integrations: parse pushed tags, and lightweight tags for git....
r2422 raw_id = commit_id[5:]
cs_data = {
feat(events): added context into events so we can track additional context of calling it
r5623 "raw_id": commit_id,
"short_id": commit_id,
"branch": None,
"git_ref_change": "tag_add",
"message": f"Added new tag {raw_id}",
"author": event.actor.full_contact,
"date": datetime.datetime.now(),
"refs": {"branches": [], "bookmarks": [], "tags": []},
integrations: parse pushed tags, and lightweight tags for git....
r2422 }
commits.append(cs_data)
dan
events: change target to source repo for pull request events...
r514
feat(events): added context into events so we can track additional context of calling it
r5623 elif commit_id.startswith("delete_branch=>"):
integrations: parse pushed tags, and lightweight tags for git....
r2422 raw_id = commit_id[15:]
cs_data = {
feat(events): added context into events so we can track additional context of calling it
r5623 "raw_id": commit_id,
"short_id": commit_id,
"branch": None,
"git_ref_change": "branch_delete",
"message": f"Deleted branch {raw_id}",
"author": event.actor.full_contact,
"date": datetime.datetime.now(),
"refs": {"branches": [], "bookmarks": [], "tags": []},
integrations: parse pushed tags, and lightweight tags for git....
r2422 }
commits.append(cs_data)
else:
try:
dan
vcs: don't use deprecated get_changeset[s] methods.
r3112 cs = vcs_repo.get_commit(commit_id)
integrations: parse pushed tags, and lightweight tags for git....
r2422 except CommitDoesNotExistError:
continue # maybe its in next repo
cs_data = cs.__json__()
feat(events): added context into events so we can track additional context of calling it
r5623 cs_data["refs"] = cs._get_refs()
integrations: parse pushed tags, and lightweight tags for git....
r2422
feat(events): added context into events so we can track additional context of calling it
r5623 cs_data["mentions"] = extract_mentioned_users(cs_data["message"])
cs_data["reviewers"] = reviewers
cs_data["url"] = RepoModel().get_commit_url(repo, cs_data["raw_id"], request=event.request)
cs_data["permalink_url"] = RepoModel().get_commit_url(
repo, cs_data["raw_id"], request=event.request, permalink=True
)
urlified_message, issues_data, errors = process_patterns(cs_data["message"], repo.repo_name)
cs_data["issues"] = issues_data
cs_data["message_html"] = urlify_commit_message(cs_data["message"], repo.repo_name)
cs_data["message_html_title"] = chop_at_smart(cs_data["message"], "\n", suffix_if_chopped="...")
dan
events: change target to source repo for pull request events...
r514 commits.append(cs_data)
dan
events: send pushed commit ids in order
r782 needed_commits.remove(commit_id)
dan
events: change target to source repo for pull request events...
r514
integrations: parse pushed tags, and lightweight tags for git....
r2422 except Exception:
feat(events): added context into events so we can track additional context of calling it
r5623 log.exception("Failed to extract commits data")
slack: updated slack integration to use the attachements for nicer formatting.
r1467 # we don't send any commits when crash happens, only full list
# matters we short circuit then.
dan
events: change target to source repo for pull request events...
r514 return []
events: added more validation of repo type events
r5124 # we failed to remove all needed_commits from all repositories
if needed_commits:
feat(events): added context into events so we can track additional context of calling it
r5623 raise ValueError(f"Unexpectedly not found {needed_commits} in all available repos {repos}")
events: added more validation of repo type events
r5124
feat(events): added context into events so we can track additional context of calling it
r5623 missing_commits = set(commit_ids) - set(c["raw_id"] for c in commits)
dan
events: change target to source repo for pull request events...
r514 if missing_commits:
feat(events): added context into events so we can track additional context of calling it
r5623 log.error("Inconsistent repository state. " "Missing commits: %s", ", ".join(missing_commits))
dan
events: change target to source repo for pull request events...
r514
return commits
def _issues_as_dict(commits):
feat(events): added context into events so we can track additional context of calling it
r5623 """Helper function to serialize issues from commits"""
dan
events: change target to source repo for pull request events...
r514 issues = {}
for commit in commits:
feat(events): added context into events so we can track additional context of calling it
r5623 for issue in commit["issues"]:
issues[issue["id"]] = issue
dan
events: change target to source repo for pull request events...
r514 return issues
dan
events: add event system for RepoEvents
r375
events: fixed missing construcors on user based events.
r1422
events: use a distinction between RhodeCodeEvent which is a base class and it used by all events, and...
r2921 class RepoEvent(RhodeCodeIntegrationEvent):
dan
events: add event system for RepoEvents
r375 """
Base class for events acting on a repository.
"""
dan
events: add serialization .to_dict() to events based on marshmallow
r379
feat(events): added context into events so we can track additional context of calling it
r5623 def __init__(self, repo, actor=None, context=None):
core: revamp of automation/scheduler/artifacts EE functionality
r5137 """
:param repo: a :class:`Repository` instance
"""
feat(events): added context into events so we can track additional context of calling it
r5623 super().__init__(actor=actor, context=context)
dan
events: add event system for RepoEvents
r375 self.repo = repo
feat(events): added context into events so we can track additional context of calling it
r5623 self.context = self._context
dan
events: add event system for RepoEvents
r375
dan
integrations: add integration support...
r411 def as_dict(self):
from rhodecode.model.repo import RepoModel
feat(events): added context into events so we can track additional context of calling it
r5623
modernize: updates for python3
r5095 data = super().as_dict()
events: ported pylons part to pyramid....
r1959
webhook: enable support of extra repo variables as replacement in template url.
r1761 extra_fields = collections.OrderedDict()
for field in self.repo.extra_fields:
extra_fields[field.field_key] = field.field_value
feat(events): added context into events so we can track additional context of calling it
r5623 data.update(
{
"repo": {
"repo_id": self.repo.repo_id,
"repo_name": self.repo.repo_name,
"repo_type": self.repo.repo_type,
"url": RepoModel().get_url(self.repo, request=self.request),
"permalink_url": RepoModel().get_url(self.repo, request=self.request, permalink=True),
"extra_fields": extra_fields,
},
"context": self.context,
dan
integrations: add integration support...
r411 }
feat(events): added context into events so we can track additional context of calling it
r5623 )
dan
integrations: add integration support...
r411 return data
dan
events: add event system for RepoEvents
r375
dan
hooks: added new hooks for comments on pull requests and commits....
r4305 class RepoCommitCommentEvent(RepoEvent):
"""
An instance of this class is emitted as an :term:`event` after a comment is made
on repository commit.
"""
events: added support for pull-request-comment and commit-comment events....
r4314
feat(events): added context into events so we can track additional context of calling it
r5623 name = "repo-commit-comment"
display_name = lazy_ugettext("repository commit comment")
description = lazy_ugettext("Event triggered after a comment was made on commit inside a repository")
events: added support for pull-request-comment and commit-comment events....
r4314
feat(events): added context into events so we can track additional context of calling it
r5623 def __init__(self, repo, commit, comment, context=None):
super().__init__(repo, context=context)
dan
hooks: added new hooks for comments on pull requests and commits....
r4305 self.commit = commit
self.comment = comment
events: added support for pull-request-comment and commit-comment events....
r4314 def as_dict(self):
modernize: updates for python3
r5095 data = super().as_dict()
feat(events): added context into events so we can track additional context of calling it
r5623 data["commit"] = {
"commit_id": self.commit.raw_id,
"commit_message": self.commit.message,
"commit_branch": self.commit.branch,
events: added support for pull-request-comment and commit-comment events....
r4314 }
feat(events): added context into events so we can track additional context of calling it
r5623 data["comment"] = {
"comment_id": self.comment.comment_id,
"comment_text": self.comment.text,
"comment_type": self.comment.comment_type,
"comment_f_path": self.comment.f_path,
"comment_line_no": self.comment.line_no,
"comment_version": self.comment.last_version,
comments: added new events for comment editing to handle them in integrations.
r4444 }
feat(events): added context into events so we can track additional context of calling it
r5623 data["contex"] = self.context
comments: added new events for comment editing to handle them in integrations.
r4444 return data
class RepoCommitCommentEditEvent(RepoEvent):
"""
An instance of this class is emitted as an :term:`event` after a comment is edited
on repository commit.
"""
feat(events): added context into events so we can track additional context of calling it
r5623 name = "repo-commit-edit-comment"
display_name = lazy_ugettext("repository commit edit comment")
description = lazy_ugettext("Event triggered after a comment was edited on commit inside a repository")
comments: added new events for comment editing to handle them in integrations.
r4444
feat(events): added context into events so we can track additional context of calling it
r5623 def __init__(self, repo, commit, comment, context=None):
super().__init__(repo, context=context)
comments: added new events for comment editing to handle them in integrations.
r4444 self.commit = commit
self.comment = comment
def as_dict(self):
modernize: updates for python3
r5095 data = super().as_dict()
feat(events): added context into events so we can track additional context of calling it
r5623 data["commit"] = {
"commit_id": self.commit.raw_id,
"commit_message": self.commit.message,
"commit_branch": self.commit.branch,
comments: added new events for comment editing to handle them in integrations.
r4444 }
feat(events): added context into events so we can track additional context of calling it
r5623 data["comment"] = {
"comment_id": self.comment.comment_id,
"comment_text": self.comment.text,
"comment_type": self.comment.comment_type,
"comment_f_path": self.comment.f_path,
"comment_line_no": self.comment.line_no,
"comment_version": self.comment.last_version,
events: added support for pull-request-comment and commit-comment events....
r4314 }
feat(events): added context into events so we can track additional context of calling it
r5623 data["context"] = "context"
events: added support for pull-request-comment and commit-comment events....
r4314 return data
dan
hooks: added new hooks for comments on pull requests and commits....
r4305
dan
events: add event system for RepoEvents
r375 class RepoPreCreateEvent(RepoEvent):
"""
An instance of this class is emitted as an :term:`event` before a repo is
created.
"""
feat(events): added context into events so we can track additional context of calling it
r5623
name = "repo-pre-create"
display_name = lazy_ugettext("repository pre create")
description = lazy_ugettext("Event triggered before repository is created")
dan
events: add event system for RepoEvents
r375
dan
integrations: add integration support...
r411 class RepoCreateEvent(RepoEvent):
dan
events: add event system for RepoEvents
r375 """
An instance of this class is emitted as an :term:`event` whenever a repo is
created.
"""
feat(events): added context into events so we can track additional context of calling it
r5623
name = "repo-create"
display_name = lazy_ugettext("repository created")
description = lazy_ugettext("Event triggered after repository was created")
dan
events: add event system for RepoEvents
r375
class RepoPreDeleteEvent(RepoEvent):
"""
An instance of this class is emitted as an :term:`event` whenever a repo is
created.
"""
feat(events): added context into events so we can track additional context of calling it
r5623
name = "repo-pre-delete"
display_name = lazy_ugettext("repository pre delete")
description = lazy_ugettext("Event triggered before a repository is deleted")
dan
events: add event system for RepoEvents
r375
dan
integrations: add integration support...
r411 class RepoDeleteEvent(RepoEvent):
dan
events: add event system for RepoEvents
r375 """
An instance of this class is emitted as an :term:`event` whenever a repo is
created.
"""
feat(events): added context into events so we can track additional context of calling it
r5623
name = "repo-delete"
display_name = lazy_ugettext("repository deleted")
description = lazy_ugettext("Event triggered after repository was deleted")
dan
events: add event system for RepoEvents
r375
class RepoVCSEvent(RepoEvent):
"""
Base class for events triggered by the VCS
"""
core: revamp of automation/scheduler/artifacts EE functionality
r5137
feat(events): added context into events so we can track additional context of calling it
r5623 name = ""
display_name = "generic_vcs_event"
def __init__(self, repo_name, extras, context=None):
dan
events: add event system for RepoEvents
r375 self.repo = Repository.get_by_repo_name(repo_name)
if not self.repo:
feat(events): added context into events so we can track additional context of calling it
r5623 raise Exception(f"repo by this name {repo_name} does not exist")
dan
events: add event system for RepoEvents
r375 self.extras = extras
feat(events): added context into events so we can track additional context of calling it
r5623 super().__init__(self.repo, context=context)
dan
events: add event system for RepoEvents
r375
dan
events: add serialization .to_dict() to events based on marshmallow
r379 @property
dan
events: fix bugs with serialization of repo/pr events and add tests for those cases
r389 def actor(self):
feat(events): added context into events so we can track additional context of calling it
r5623 if self.extras.get("username"):
return User.get_by_username(self.extras["username"])
dan
events: add serialization .to_dict() to events based on marshmallow
r379
@property
dan
events: fix bugs with serialization of repo/pr events and add tests for those cases
r389 def actor_ip(self):
feat(events): added context into events so we can track additional context of calling it
r5623 if self.extras.get("ip"):
return self.extras["ip"]
dan
events: add serialization .to_dict() to events based on marshmallow
r379
events: expose server_url for repo events.
r649 @property
def server_url(self):
feat(events): added context into events so we can track additional context of calling it
r5623 if self.extras.get("server_url"):
return self.extras["server_url"]
events: expose server_url for repo events.
r649
pyramid: ported pyramid routing for events
r2016 @property
def request(self):
feat(events): added context into events so we can track additional context of calling it
r5623 return self.extras.get("request") or self.get_request()
pyramid: ported pyramid routing for events
r2016
dan
events: add event system for RepoEvents
r375
class RepoPrePullEvent(RepoVCSEvent):
"""
An instance of this class is emitted as an :term:`event` before commits
are pulled from a repo.
"""
feat(events): added context into events so we can track additional context of calling it
r5623
name = "repo-pre-pull"
display_name = lazy_ugettext("repository pre pull")
description = lazy_ugettext("Event triggered before repository code is pulled")
dan
events: add event system for RepoEvents
r375
class RepoPullEvent(RepoVCSEvent):
"""
An instance of this class is emitted as an :term:`event` after commits
are pulled from a repo.
"""
feat(events): added context into events so we can track additional context of calling it
r5623
name = "repo-pull"
display_name = lazy_ugettext("repository pull")
description = lazy_ugettext("Event triggered after repository code was pulled")
dan
events: add event system for RepoEvents
r375
class RepoPrePushEvent(RepoVCSEvent):
"""
An instance of this class is emitted as an :term:`event` before commits
are pushed to a repo.
"""
feat(events): added context into events so we can track additional context of calling it
r5623
name = "repo-pre-push"
display_name = lazy_ugettext("repository pre push")
description = lazy_ugettext("Event triggered before the code is pushed to a repository")
dan
events: add event system for RepoEvents
r375
class RepoPushEvent(RepoVCSEvent):
"""
An instance of this class is emitted as an :term:`event` after commits
are pushed to a repo.
:param extras: (optional) dict of data from proxied VCS actions
"""
feat(events): added context into events so we can track additional context of calling it
r5623 name = "repo-push"
display_name = lazy_ugettext("repository push")
description = lazy_ugettext("Event triggered after the code was pushed to a repository")
def __init__(self, repo_name, pushed_commit_ids, extras, context=None):
super().__init__(repo_name, extras, context=context)
dan
events: add event system for RepoEvents
r375 self.pushed_commit_ids = pushed_commit_ids
integrations: parse pushed tags, and lightweight tags for git....
r2422 self.new_refs = extras.new_refs
dan
events: add event system for RepoEvents
r375
dan
integrations: add integration support...
r411 def as_dict(self):
modernize: updates for python3
r5095 data = super().as_dict()
events: expose permalink urls for different set of object....
r1788
def branch_url(branch_name):
feat(events): added context into events so we can track additional context of calling it
r5623 return "{}/changelog?branch={}".format(data["repo"]["url"], branch_name)
dan
integrations: add integration support...
r411
integrations: parse pushed tags, and lightweight tags for git....
r2422 def tag_url(tag_name):
feat(events): added context into events so we can track additional context of calling it
r5623 return "{}/files/{}/".format(data["repo"]["url"], tag_name)
integrations: parse pushed tags, and lightweight tags for git....
r2422
feat(events): added context into events so we can track additional context of calling it
r5623 commits = _commits_as_dict(self, commit_ids=self.pushed_commit_ids, repos=[self.repo])
dan
events: use branch from previous commit for repo push event commits...
r815
last_branch = None
for commit in reversed(commits):
feat(events): added context into events so we can track additional context of calling it
r5623 commit["branch"] = commit["branch"] or last_branch
last_branch = commit["branch"]
dan
events: change target to source repo for pull request events...
r514 issues = _issues_as_dict(commits)
dan
integrations: add integration support...
r411
integrations: parse pushed tags, and lightweight tags for git....
r2422 branches = set()
tags = set()
for commit in commits:
feat(events): added context into events so we can track additional context of calling it
r5623 if commit["refs"]["tags"]:
for tag in commit["refs"]["tags"]:
integrations: parse pushed tags, and lightweight tags for git....
r2422 tags.add(tag)
feat(events): added context into events so we can track additional context of calling it
r5623 if commit["branch"]:
branches.add(commit["branch"])
integrations: parse pushed tags, and lightweight tags for git....
r2422
# maybe we have branches in new_refs ?
try:
feat(events): added context into events so we can track additional context of calling it
r5623 branches = branches.union(set(self.new_refs["branches"]))
integrations: parse pushed tags, and lightweight tags for git....
r2422 except Exception:
pass
feat(events): added context into events so we can track additional context of calling it
r5623 branches = [{"name": branch, "url": branch_url(branch)} for branch in branches]
dan
integrations: add integration support...
r411
integrations: parse pushed tags, and lightweight tags for git....
r2422 # maybe we have branches in new_refs ?
try:
feat(events): added context into events so we can track additional context of calling it
r5623 tags = tags.union(set(self.new_refs["tags"]))
integrations: parse pushed tags, and lightweight tags for git....
r2422 except Exception:
pass
feat(events): added context into events so we can track additional context of calling it
r5623 tags = [{"name": tag, "url": tag_url(tag)} for tag in tags]
integrations: parse pushed tags, and lightweight tags for git....
r2422
feat(events): added context into events so we can track additional context of calling it
r5623 data["push"] = {
"commits": commits,
"issues": issues,
"branches": branches,
"tags": tags,
dan
integrations: add integration support...
r411 }
Martin Bornhold
logging: Use __name__ when requesting a logger
r504 return data