diff --git a/pagure/hooks/__init__.py b/pagure/hooks/__init__.py index 9a17e80..4276200 100644 --- a/pagure/hooks/__init__.py +++ b/pagure/hooks/__init__.py @@ -73,12 +73,13 @@ class BaseRunner(object): username (string): The user performing a push project (model.Project): The project this call is made for repotype (string): Value of lib.REPOTYPES indicating for which - repo the currnet call is + repo the current call is repodir (string): Directory where a clone of the specified repo is located. Do note that this might or might not be a writable clone. changes (dict): A dict with keys being the ref to update, values being a tuple of (from, to). + For example: {'refs/heads/master': (hash_from, hash_to), ...} """ if hooktype == "pre-receive": cls.pre_receive( @@ -327,7 +328,7 @@ def run_project_hooks( sys.exit(1) # Now we run the hooks for plugins - for plugin, _ in get_enabled_plugins(project): + for plugin, _ in get_enabled_plugins(project, with_default=True): if not plugin.runner: if debug: print( diff --git a/pagure/hooks/default.py b/pagure/hooks/default.py index 51d625c..94d8623 100644 --- a/pagure/hooks/default.py +++ b/pagure/hooks/default.py @@ -8,9 +8,13 @@ """ -from __future__ import unicode_literals +from __future__ import unicode_literals, print_function +import logging + +import pygit2 import sqlalchemy as sa +import six import wtforms try: @@ -20,9 +24,17 @@ except ImportError: from sqlalchemy.orm import relation from sqlalchemy.orm import backref -from pagure.hooks import BaseHook +import pagure.config +import pagure.exceptions +import pagure.lib.tasks +import pagure.lib.tasks_services +import pagure.utils +from pagure.hooks import BaseHook, BaseRunner from pagure.lib.model import BASE, Project -from pagure.utils import get_repo_path + + +_config = pagure.config.reload_config() +_log = logging.getLogger(__name__) class DefaultTable(BASE): @@ -55,6 +67,253 @@ class DefaultTable(BASE): ) +def send_fedmsg_notifications(project, topic, msg): + """ If the user asked for fedmsg notifications on commit, this will + do it. + """ + import fedmsg + + config = fedmsg.config.load_config([], None) + config["active"] = True + config["endpoints"]["relay_inbound"] = config["relay_inbound"] + fedmsg.init(name="relay_inbound", **config) + + pagure.lib.notify.log( + project=project, + topic=topic, + msg=msg, + redis=None, # web-hook notification are handled separately + ) + + +def send_webhook_notifications(project, topic, msg): + """ If the user asked for webhook notifications on commit, this will + do it. + """ + + pagure.lib.tasks_services.webhook_notification.delay( + topic=topic, + msg=msg, + namespace=project.namespace, + name=project.name, + user=project.user.username if project.is_fork else None, + ) + + +def send_notifications(session, project, repodir, user, refname, revs, forced): + """ Send out-going notifications about the commits that have just been + pushed. + """ + + auths = set() + for rev in revs: + email = pagure.lib.git.get_author_email(rev, repodir) + name = pagure.lib.git.get_author(rev, repodir) + author = pagure.lib.search_user(session, email=email) or name + auths.add(author) + + authors = [] + for author in auths: + if not isinstance(author, six.string_types): + author = author.to_json(public=True) + authors.append(author) + + if revs: + revs.reverse() + print("* Publishing information for %i commits" % len(revs)) + + topic = "git.receive" + msg = dict( + total_commits=len(revs), + start_commit=revs[0], + end_commit=revs[-1], + branch=refname, + forced=forced, + authors=list(authors), + agent=user, + repo=project.to_json(public=True) + if not isinstance(project, six.string_types) + else project, + ) + + fedmsg_hook = pagure.lib.plugins.get_plugin("Fedmsg") + fedmsg_hook.db_object() + + always_fedmsg = _config.get("ALWAYS_FEDMSG_ON_COMMITS") or None + + if always_fedmsg or ( + project.fedmsg_hook and project.fedmsg_hook.active + ): + try: + print(" - to fedmsg") + send_fedmsg_notifications(project, topic, msg) + except Exception: + _log.exception( + "Error sending fedmsg notifications on commit push" + ) + if project.settings.get("Web-hooks") and not project.private: + try: + print(" - to web-hooks") + send_webhook_notifications(project, topic, msg) + except Exception: + _log.exception( + "Error sending web-hook notifications on commit push" + ) + + if ( + _config.get("PAGURE_CI_SERVICES") + and project.ci_hook + and project.ci_hook.active_commit + and not project.private + ): + pagure.lib.tasks_services.trigger_ci_build.delay( + project_name=project.fullname, + cause=revs[-1], + branch=refname, + ci_type=project.ci_hook.ci_type, + ) + + +def inform_pull_request_urls( + session, project, commits, refname, default_branch +): + """ Inform the user about the URLs to open a new pull-request or visit + the existing one. + """ + target_repo = project + if project.is_fork: + target_repo = project.parent + + if ( + commits + and refname != default_branch + and target_repo.settings.get("pull_requests", True) + ): + print() + prs = pagure.lib.search_pull_requests( + session, + project_id_from=project.id, + status="Open", + branch_from=refname, + ) + # Link to existing PRs if there are any + seen = len(prs) != 0 + for pr in prs: + # Link tickets with pull-requests if the commit mentions it + pagure.lib.tasks.link_pr_to_ticket.delay(pr.uid) + + # Inform the user about the PR + print("View pull-request for %s" % refname) + print( + " %s/%s/pull-request/%s" + % (_config["APP_URL"].rstrip("/"), pr.project.url_path, pr.id) + ) + # If no existing PRs, provide the link to open one + if not seen: + print("Create a pull-request for %s" % refname) + print( + " %s/%s/diff/%s..%s" + % ( + _config["APP_URL"].rstrip("/"), + project.url_path, + default_branch, + refname, + ) + ) + print() + + +class DefaultRunner(BaseRunner): + """ Runner for the default hook.""" + + @staticmethod + def post_receive(session, username, project, repotype, repodir, changes): + """ Run the default post-receive hook. + + For args, see BaseRunner.runhook. + """ + if repotype != "main": + if _config.get("HOOK_DEBUG", False): + print("Default hook only runs on the main project repository") + return + + if changes: + # Retrieve the default branch + repo_obj = pygit2.Repository(repodir) + default_branch = None + if not repo_obj.is_empty and not repo_obj.head_is_unborn: + default_branch = repo_obj.head.shorthand + + for refname in changes: + (oldrev, newrev) = changes[refname] + + forced = False + if set(newrev) == set(["0"]): + print( + "Deleting a reference/branch, so we won't run the " + "pagure hook" + ) + return + elif set(oldrev) == set(["0"]): + oldrev = "^%s" % oldrev + elif pagure.lib.git.is_forced_push(oldrev, newrev, repodir): + forced = True + base = pagure.lib.git.get_base_revision( + oldrev, newrev, repodir + ) + if base: + oldrev = base[0] + + refname = refname.replace("refs/heads/", "") + commits = pagure.lib.git.get_revs_between( + oldrev, newrev, repodir, refname + ) + + if refname == default_branch: + print( + "Sending to redis to log activity and send commit " + "notification emails" + ) + else: + print("Sending to redis to send commit notification emails") + + # This is logging the commit to the log table in the DB so we can + # render commits in the calendar heatmap. + # It is also sending emails about commits to people using the + # 'watch' feature to be made aware of new commits. + pagure.lib.tasks_services.log_commit_send_notifications.delay( + name=project.name, + commits=commits, + abspath=repodir, + branch=refname, + default_branch=default_branch, + namespace=project.namespace, + username=project.user.user if project.is_fork else None, + ) + + # This one is sending fedmsg and web-hook notifications for project + # that set them up + send_notifications( + session, project, repodir, username, refname, commits, forced + ) + + # Now display to the user if this isn't the default branch links to + # open a new pr or review the existing one + inform_pull_request_urls( + session, project, commits, refname, default_branch + ) + + # Schedule refresh of all opened PRs + parent = project.parent or project + pagure.lib.tasks.refresh_pr_cache.delay( + parent.name, + parent.namespace, + parent.user.user if parent.is_fork else None, + ) + + session.remove() + + class DefaultForm(FlaskForm): """ Form to configure the default hook. """ @@ -80,27 +339,4 @@ class Default(BaseHook): db_object = DefaultTable backref = "default_hook" form_fields = ["active"] - - @classmethod - def install(cls, project, dbobj): - """ Method called to install the hook for a project. - - :arg project: a ``pagure.model.Project`` object to which the hook - should be installed - - """ - repopaths = [get_repo_path(project)] - - cls.base_install(repopaths, dbobj, "default", "default_hook.py") - - @classmethod - def remove(cls, project): - """ Method called to remove the hook of a project. - - :arg project: a ``pagure.model.Project`` object to which the hook - should be installed - - """ - repopaths = [get_repo_path(project)] - - cls.base_remove(repopaths, "default") + runner = DefaultRunner diff --git a/pagure/hooks/fedmsg.py b/pagure/hooks/fedmsg.py index 65efc76..c0ce4e6 100644 --- a/pagure/hooks/fedmsg.py +++ b/pagure/hooks/fedmsg.py @@ -20,7 +20,7 @@ except ImportError: from sqlalchemy.orm import relation from sqlalchemy.orm import backref -from pagure.hooks import BaseHook +from pagure.hooks import BaseHook, BaseRunner from pagure.lib.model import BASE, Project @@ -55,6 +55,14 @@ class FedmsgTable(BASE): ) +class FedmsgRunner(BaseRunner): + """ Runner for the fedmsg hook, it does nothing as all the magic is + part of the default hook/runner. + """ + + pass + + class FedmsgForm(FlaskForm): """ Form to configure the fedmsg hook. """ @@ -82,6 +90,7 @@ class Fedmsg(BaseHook): db_object = FedmsgTable backref = "fedmsg_hook" form_fields = ["active"] + runner = FedmsgRunner @classmethod def install(cls, project, dbobj): diff --git a/pagure/hooks/files/default_hook.py b/pagure/hooks/files/default_hook.py deleted file mode 100755 index 5c4b056..0000000 --- a/pagure/hooks/files/default_hook.py +++ /dev/null @@ -1,294 +0,0 @@ -#!/usr/bin/env python - - -"""Pagure specific hook to be added to all projects in pagure by default. -""" -from __future__ import print_function, unicode_literals - -import os -import logging -import sys - - -if "PAGURE_CONFIG" not in os.environ and os.path.exists( - "/etc/pagure/pagure.cfg" -): - os.environ["PAGURE_CONFIG"] = "/etc/pagure/pagure.cfg" - - -import pygit2 # noqa: E402 -import six # noqa: E402 - -import pagure # noqa: E402 -import pagure.flask_app # noqa: E402 -import pagure.exceptions # noqa: E402 -import pagure.lib.link # noqa: E402 -import pagure.lib.tasks # noqa: E402 -import pagure.lib.tasks_services # noqa: E402 - - -_config = pagure.config.reload_config() -_log = logging.getLogger(__name__) -abspath = os.path.abspath(os.environ["GIT_DIR"]) - - -def send_fedmsg_notifications(project, topic, msg): - """ If the user asked for fedmsg notifications on commit, this will - do it. - """ - import fedmsg - - config = fedmsg.config.load_config([], None) - config["active"] = True - config["endpoints"]["relay_inbound"] = config["relay_inbound"] - fedmsg.init(name="relay_inbound", **config) - - pagure.lib.notify.log( - project=project, - topic=topic, - msg=msg, - redis=None, # web-hook notification are handled separately - ) - - -def send_webhook_notifications(project, topic, msg): - """ If the user asked for webhook notifications on commit, this will - do it. - """ - - pagure.lib.tasks_services.webhook_notification.delay( - topic=topic, - msg=msg, - namespace=project.namespace, - name=project.name, - user=project.user.username if project.is_fork else None, - ) - - -def send_notifications(session, project, refname, revs, forced): - """ Send out-going notifications about the commits that have just been - pushed. - """ - - auths = set() - for rev in revs: - email = pagure.lib.git.get_author_email(rev, abspath) - name = pagure.lib.git.get_author(rev, abspath) - author = pagure.lib.search_user(session, email=email) or name - auths.add(author) - - authors = [] - for author in auths: - if not isinstance(author, six.string_types): - author = author.to_json(public=True) - authors.append(author) - - if revs: - revs.reverse() - print("* Publishing information for %i commits" % len(revs)) - - topic = "git.receive" - msg = dict( - total_commits=len(revs), - start_commit=revs[0], - end_commit=revs[-1], - branch=refname, - forced=forced, - authors=list(authors), - agent=os.environ["GL_USER"], - repo=project.to_json(public=True) - if not isinstance(project, six.string_types) - else project, - ) - - fedmsg_hook = pagure.lib.plugins.get_plugin("Fedmsg") - fedmsg_hook.db_object() - - always_fedmsg = _config.get("ALWAYS_FEDMSG_ON_COMMITS") or None - - if always_fedmsg or ( - project.fedmsg_hook and project.fedmsg_hook.active - ): - try: - print(" - to fedmsg") - send_fedmsg_notifications(project, topic, msg) - except Exception: - _log.exception( - "Error sending fedmsg notifications on commit push" - ) - if project.settings.get("Web-hooks") and not project.private: - try: - print(" - to web-hooks") - send_webhook_notifications(project, topic, msg) - except Exception: - _log.exception( - "Error sending web-hook notifications on commit push" - ) - - if ( - _config.get("PAGURE_CI_SERVICES") - and project.ci_hook - and project.ci_hook.active_commit - and not project.private - ): - pagure.lib.tasks_services.trigger_ci_build.delay( - project_name=project.fullname, - cause=revs[-1], - branch=refname, - ci_type=project.ci_hook.ci_type, - ) - - -def inform_pull_request_urls( - session, project, commits, refname, default_branch -): - """ Inform the user about the URLs to open a new pull-request or visit - the existing one. - """ - target_repo = project - if project.is_fork: - target_repo = project.parent - - if ( - commits - and refname != default_branch - and target_repo.settings.get("pull_requests", True) - ): - print() - prs = pagure.lib.search_pull_requests( - session, - project_id_from=project.id, - status="Open", - branch_from=refname, - ) - # Link to existing PRs if there are any - seen = len(prs) != 0 - for pr in prs: - # Link tickets with pull-requests if the commit mentions it - pagure.lib.tasks.link_pr_to_ticket.delay(pr.uid) - - # Inform the user about the PR - print("View pull-request for %s" % refname) - print( - " %s/%s/pull-request/%s" - % (_config["APP_URL"].rstrip("/"), pr.project.url_path, pr.id) - ) - # If no existing PRs, provide the link to open one - if not seen: - print("Create a pull-request for %s" % refname) - print( - " %s/%s/diff/%s..%s" - % ( - _config["APP_URL"].rstrip("/"), - project.url_path, - default_branch, - refname, - ) - ) - print() - - -def run_as_post_receive_hook(): - - repo = pagure.lib.git.get_repo_name(abspath) - username = pagure.lib.git.get_username(abspath) - namespace = pagure.lib.git.get_repo_namespace(abspath) - if _config.get("HOOK_DEBUG", False): - print("repo:", repo) - print("user:", username) - print("namespace:", namespace) - - session = pagure.lib.create_session(_config["DB_URL"]) - - project = pagure.lib._get_project( - session, repo, user=username, namespace=namespace - ) - - for line in sys.stdin: - if _config.get("HOOK_DEBUG", False): - print(line) - (oldrev, newrev, refname) = line.strip().split(" ", 2) - - if _config.get("HOOK_DEBUG", False): - print(" -- Old rev") - print(oldrev) - print(" -- New rev") - print(newrev) - print(" -- Ref name") - print(refname) - - # Retrieve the default branch - repo_obj = pygit2.Repository(abspath) - default_branch = None - if not repo_obj.is_empty and not repo_obj.head_is_unborn: - default_branch = repo_obj.head.shorthand - - forced = False - if set(newrev) == set(["0"]): - print( - "Deleting a reference/branch, so we won't run the " - "pagure hook" - ) - return - elif set(oldrev) == set(["0"]): - oldrev = "^%s" % oldrev - elif pagure.lib.git.is_forced_push(oldrev, newrev, abspath): - forced = True - base = pagure.lib.git.get_base_revision(oldrev, newrev, abspath) - if base: - oldrev = base[0] - - refname = refname.replace("refs/heads/", "") - commits = pagure.lib.git.get_revs_between( - oldrev, newrev, abspath, refname - ) - - if refname == default_branch: - print( - "Sending to redis to log activity and send commit " - "notification emails" - ) - else: - print("Sending to redis to send commit notification emails") - - # This is logging the commit to the log table in the DB so we can - # render commits in the calendar heatmap. - # It is also sending emails about commits to people using the - # 'watch' feature to be made aware of new commits. - pagure.lib.tasks_services.log_commit_send_notifications.delay( - name=repo, - commits=commits, - abspath=abspath, - branch=refname, - default_branch=default_branch, - namespace=namespace, - username=username, - ) - - # This one is sending fedmsg and web-hook notifications for project - # that set them up - send_notifications(session, project, refname, commits, forced) - - # Now display to the user if this isn't the default branch links to - # open a new pr or review the existing one - inform_pull_request_urls( - session, project, commits, refname, default_branch - ) - - # Schedule refresh of all opened PRs - parent = project.parent or project - pagure.lib.tasks.refresh_pr_cache.delay( - parent.name, - parent.namespace, - parent.user.user if parent.is_fork else None, - ) - - session.remove() - - -def main(args): - run_as_post_receive_hook() - - -if __name__ == "__main__": - main(sys.argv[1:]) diff --git a/pagure/hooks/files/default_hook.py b/pagure/hooks/files/default_hook.py new file mode 120000 index 0000000..6be2006 --- /dev/null +++ b/pagure/hooks/files/default_hook.py @@ -0,0 +1 @@ +/does/not/exist \ No newline at end of file diff --git a/pagure/hooks/files/hookrunner b/pagure/hooks/files/hookrunner index b59732a..c583c97 100755 --- a/pagure/hooks/files/hookrunner +++ b/pagure/hooks/files/hookrunner @@ -11,6 +11,11 @@ import os import sys +if "PAGURE_CONFIG" not in os.environ and os.path.exists( + "/etc/pagure/pagure.cfg" +): + os.environ["PAGURE_CONFIG"] = "/etc/pagure/pagure.cfg" + import pagure.lib from pagure.hooks import run_hook_file diff --git a/pagure/hooks/files/mirror.py b/pagure/hooks/files/mirror.py deleted file mode 100755 index 77510cf..0000000 --- a/pagure/hooks/files/mirror.py +++ /dev/null @@ -1,63 +0,0 @@ -#!/usr/bin/env python - - -"""Pagure specific hook to mirror a repo to another location. -""" -from __future__ import unicode_literals, print_function - - -import logging -import os -import sys - - -if "PAGURE_CONFIG" not in os.environ and os.path.exists( - "/etc/pagure/pagure.cfg" -): - os.environ["PAGURE_CONFIG"] = "/etc/pagure/pagure.cfg" - - -import pagure.config # noqa: E402 -import pagure.exceptions # noqa: E402 -import pagure.lib # noqa: E402 -import pagure.lib.tasks_mirror # noqa: E402 -import pagure.ui.plugins # noqa: E402 - - -_log = logging.getLogger(__name__) -_config = pagure.config.config -abspath = os.path.abspath(os.environ["GIT_DIR"]) - - -def main(args): - - repo = pagure.lib.git.get_repo_name(abspath) - username = pagure.lib.git.get_username(abspath) - namespace = pagure.lib.git.get_repo_namespace(abspath) - if _config.get("HOOK_DEBUG", False): - print("repo:", repo) - print("user:", username) - print("namespace:", namespace) - - session = pagure.lib.create_session(_config["DB_URL"]) - project = pagure.lib._get_project( - session, repo, user=username, namespace=namespace - ) - - if not project: - print("Could not find a project corresponding to this git repo") - session.close() - return 1 - - pagure.lib.tasks_mirror.mirror_project.delay( - username=project.user.user if project.is_fork else None, - namespace=project.namespace, - name=project.name, - ) - - session.close() - return 0 - - -if __name__ == "__main__": - main(sys.argv[1:]) diff --git a/pagure/hooks/files/mirror.py b/pagure/hooks/files/mirror.py new file mode 120000 index 0000000..6be2006 --- /dev/null +++ b/pagure/hooks/files/mirror.py @@ -0,0 +1 @@ +/does/not/exist \ No newline at end of file diff --git a/pagure/hooks/files/pagure_block_unsigned.py b/pagure/hooks/files/pagure_block_unsigned.py deleted file mode 100755 index bca674e..0000000 --- a/pagure/hooks/files/pagure_block_unsigned.py +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env python - - -"""Pagure specific hook to block commit not having a 'Signed-off-by' -statement. -""" - -from __future__ import print_function, unicode_literals - -import os -import sys - - -if "PAGURE_CONFIG" not in os.environ and os.path.exists( - "/etc/pagure/pagure.cfg" -): - os.environ["PAGURE_CONFIG"] = "/etc/pagure/pagure.cfg" - - -import pagure # noqa: E402 -import pagure.exceptions # noqa: E402 -import pagure.lib.link # noqa: E402 -import pagure.ui.plugins # noqa: E402 - -_config = pagure.config.config -abspath = os.path.abspath(os.environ["GIT_DIR"]) - - -def run_as_pre_receive_hook(): - - for line in sys.stdin: - if _config.get("HOOK_DEBUG", False): - print(line) - (oldrev, newrev, refname) = line.strip().split(" ", 2) - - if _config.get("HOOK_DEBUG", False): - print(" -- Old rev") - print(oldrev) - print(" -- New rev") - print(newrev) - print(" -- Ref name") - print(refname) - - if set(newrev) == set(["0"]): - print( - "Deleting a reference/branch, so we won't run the " - "hook to block unsigned commits" - ) - return - - commits = pagure.lib.git.get_revs_between( - oldrev, newrev, abspath, refname - ) - for commit in commits: - if _config.get("HOOK_DEBUG", False): - print("Processing commit: %s" % commit) - signed = False - for line in pagure.lib.git.read_git_lines( - ["log", "--no-walk", commit], abspath - ): - if line.lower().strip().startswith("signed-off-by"): - signed = True - break - if _config.get("HOOK_DEBUG", False): - print(" - Commit: %s is signed: %s" % (commit, signed)) - if not signed: - print("Commit %s is not signed" % commit) - sys.exit(1) - - -def main(args): - run_as_pre_receive_hook() - - -if __name__ == "__main__": - main(sys.argv[1:]) diff --git a/pagure/hooks/files/pagure_block_unsigned.py b/pagure/hooks/files/pagure_block_unsigned.py new file mode 120000 index 0000000..6be2006 --- /dev/null +++ b/pagure/hooks/files/pagure_block_unsigned.py @@ -0,0 +1 @@ +/does/not/exist \ No newline at end of file diff --git a/pagure/hooks/files/pagure_force_commit_hook.py b/pagure/hooks/files/pagure_force_commit_hook.py deleted file mode 100755 index 8bb246c..0000000 --- a/pagure/hooks/files/pagure_force_commit_hook.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python - - -"""Pagure specific hook to block non-fastforward pushes. -""" - -from __future__ import print_function, unicode_literals - -import os -import sys - - -if "PAGURE_CONFIG" not in os.environ and os.path.exists( - "/etc/pagure/pagure.cfg" -): - os.environ["PAGURE_CONFIG"] = "/etc/pagure/pagure.cfg" - - -import pagure # noqa: E402 -import pagure.exceptions # noqa: E402 -import pagure.lib.link # noqa: E402 -import pagure.lib.plugins # noqa: E402 - - -_config = pagure.config.config -abspath = os.path.abspath(os.environ["GIT_DIR"]) - - -def run_as_pre_receive_hook(): - reponame = pagure.lib.git.get_repo_name(abspath) - namespace = pagure.lib.git.get_repo_namespace(abspath) - username = pagure.lib.git.get_username(abspath) - session = pagure.lib.create_session(_config["DB_URL"]) - if _config.get("HOOK_DEBUG", False): - print("repo: ", reponame) - print("user: ", username) - print("namspaces:", namespace) - - repo = pagure.lib._get_project( - session, reponame, user=username, namespace=namespace - ) - - if not repo: - print( - "Unknown repo %s of username: %s in namespace %s" - % (reponame, username, namespace) - ) - session.close() - sys.exit(1) - - plugin = pagure.lib.plugins.get_plugin("Block non fast-forward pushes") - plugin.db_object() - # Get the list of branches - branches = [] - if repo.pagure_force_commit_hook: - branches = [ - branch.strip() - for branch in repo.pagure_force_commit_hook.branches.split(",") - if branch.strip() - ] - - for line in sys.stdin: - if _config.get("HOOK_DEBUG", False): - print(line) - (oldrev, newrev, refname) = line.strip().split(" ", 2) - - refname = refname.replace("refs/heads/", "") - if refname in branches or branches == ["*"]: - if _config.get("HOOK_DEBUG", False): - print(" -- Old rev") - print(oldrev) - print(" -- New rev") - print(newrev) - print(" -- Ref name") - print(refname) - - if set(newrev) == set(["0"]): - print("Deletion is forbidden") - session.close() - sys.exit(1) - elif pagure.lib.git.is_forced_push(oldrev, newrev, abspath): - print("Non fast-forward push are forbidden") - session.close() - sys.exit(1) - - session.close() - - -def main(args): - run_as_pre_receive_hook() - - -if __name__ == "__main__": - main(sys.argv[1:]) diff --git a/pagure/hooks/files/pagure_force_commit_hook.py b/pagure/hooks/files/pagure_force_commit_hook.py new file mode 120000 index 0000000..6be2006 --- /dev/null +++ b/pagure/hooks/files/pagure_force_commit_hook.py @@ -0,0 +1 @@ +/does/not/exist \ No newline at end of file diff --git a/pagure/hooks/files/pagure_hook.py b/pagure/hooks/files/pagure_hook.py deleted file mode 100755 index 6718761..0000000 --- a/pagure/hooks/files/pagure_hook.py +++ /dev/null @@ -1,239 +0,0 @@ -#!/usr/bin/env python - - -"""Pagure specific hook to add comment on issues if the commits fixes or -relates to an issue. -""" - -from __future__ import print_function, unicode_literals - -import logging -import os -import sys - -import pygit2 - -from sqlalchemy.exc import SQLAlchemyError - -if "PAGURE_CONFIG" not in os.environ and os.path.exists( - "/etc/pagure/pagure.cfg" -): - os.environ["PAGURE_CONFIG"] = "/etc/pagure/pagure.cfg" - - -import pagure.config # noqa: E402 -import pagure.exceptions # noqa: E402 -import pagure.lib.link # noqa: E402 - - -_log = logging.getLogger(__name__) -_config = pagure.config.config - -abspath = os.path.abspath(os.environ["GIT_DIR"]) - - -def generate_revision_change_log(new_commits_list): - - print("Detailed log of new commits:\n\n") - commitid = None - for line in pagure.lib.git.read_git_lines( - ["log", "--no-walk"] + new_commits_list + ["--"], abspath - ): - if line.startswith("commit"): - commitid = line.split("commit ")[-1] - - line = line.strip() - session = pagure.lib.create_session(_config["DB_URL"]) - print("*", line) - for relation in pagure.lib.link.get_relation( - session, - pagure.lib.git.get_repo_name(abspath), - pagure.lib.git.get_username(abspath), - pagure.lib.git.get_repo_namespace(abspath), - line, - "fixes", - include_prs=True, - ): - if _config.get("HOOK_DEBUG", False): - print(commitid, relation) - fixes_relation(commitid, relation, session, _config.get("APP_URL")) - - for issue in pagure.lib.link.get_relation( - session, - pagure.lib.git.get_repo_name(abspath), - pagure.lib.git.get_username(abspath), - pagure.lib.git.get_repo_namespace(abspath), - line, - "relates", - ): - if _config.get("HOOK_DEBUG", False): - print(commitid, issue) - relates_commit(commitid, issue, session, _config.get("APP_URL")) - - session.close() - - -def relates_commit(commitid, issue, session, app_url=None): - """ Add a comment to an issue that this commit relates to it. """ - - url = "../%s" % commitid[:8] - if app_url: - if app_url.endswith("/"): - app_url = app_url[:-1] - project = issue.project.fullname - if issue.project.is_fork: - project = "fork/%s" % project - url = "%s/%s/c/%s" % (app_url, project, commitid[:8]) - - comment = """ Commit [%s](%s) relates to this ticket""" % ( - commitid[:8], - url, - ) - - user = os.environ.get( - "GL_USER", pagure.lib.git.get_author_email(commitid, abspath) - ) - - try: - pagure.lib.add_issue_comment( - session, - issue=issue, - comment=comment, - user=user, - ticketfolder=_config["TICKETS_FOLDER"], - ) - session.commit() - except pagure.exceptions.PagureException as err: - print(err) - except SQLAlchemyError as err: # pragma: no cover - session.rollback() - _log.exception(err) - - -def fixes_relation(commitid, relation, session, app_url=None): - """ Add a comment to an issue or PR that this commit fixes it and update - the status if the commit is in the master branch. """ - - url = "../c/%s" % commitid[:8] - if app_url: - if app_url.endswith("/"): - app_url = app_url[:-1] - project = relation.project.fullname - if relation.project.is_fork: - project = "fork/%s" % project - url = "%s/%s/c/%s" % (app_url, project, commitid[:8]) - - comment = """ Commit [%s](%s) fixes this %s""" % ( - commitid[:8], - url, - relation.isa, - ) - - user = os.environ.get( - "GL_USER", pagure.lib.git.get_author_email(commitid, abspath) - ) - - try: - if relation.isa == "issue": - pagure.lib.add_issue_comment( - session, - issue=relation, - comment=comment, - user=user, - ticketfolder=_config["TICKETS_FOLDER"], - ) - elif relation.isa == "pull-request": - pagure.lib.add_pull_request_comment( - session, - request=relation, - commit=None, - tree_id=None, - filename=None, - row=None, - comment=comment, - user=user, - requestfolder=_config["REQUESTS_FOLDER"], - ) - session.commit() - except pagure.exceptions.PagureException as err: - print(err) - except SQLAlchemyError as err: # pragma: no cover - session.rollback() - _log.exception(err) - - try: - if relation.isa == "issue": - pagure.lib.edit_issue( - session, - relation, - ticketfolder=_config["TICKETS_FOLDER"], - user=user, - status="Closed", - close_status="Fixed", - ) - elif relation.isa == "pull-request": - pagure.lib.close_pull_request( - session, - relation, - requestfolder=_config["REQUESTS_FOLDER"], - user=user, - merged=True, - ) - session.commit() - except pagure.exceptions.PagureException as err: - print(err) - except SQLAlchemyError as err: # pragma: no cover - session.rollback() - print("ERROR", err) - _log.exception(err) - - -def run_as_post_receive_hook(): - - for line in sys.stdin: - if _config.get("HOOK_DEBUG", False): - print(line) - (oldrev, newrev, refname) = line.strip().split(" ", 2) - - if _config.get("HOOK_DEBUG", False): - print(" -- Old rev") - print(oldrev) - print(" -- New rev") - print(newrev) - print(" -- Ref name") - print(refname) - - # Retrieve the default branch - repo_obj = pygit2.Repository(abspath) - default_branch = None - if not repo_obj.is_empty and not repo_obj.head_is_unborn: - default_branch = repo_obj.head.shorthand - - # Skip all branch but the default one - refname = refname.replace("refs/heads/", "") - if refname != default_branch: - continue - - if set(newrev) == set(["0"]): - print( - "Deleting a reference/branch, so we won't run the " - "pagure hook" - ) - return - - generate_revision_change_log( - pagure.lib.git.get_revs_between(oldrev, newrev, abspath, refname) - ) - - if _config.get("HOOK_DEBUG", False): - print("ns :", pagure.lib.git.get_repo_namespace(abspath)) - print("repo:", pagure.lib.git.get_repo_name(abspath)) - print("user:", pagure.lib.git.get_username(abspath)) - - -def main(args): - run_as_post_receive_hook() - - -if __name__ == "__main__": - main(sys.argv[1:]) diff --git a/pagure/hooks/files/pagure_hook.py b/pagure/hooks/files/pagure_hook.py new file mode 120000 index 0000000..6be2006 --- /dev/null +++ b/pagure/hooks/files/pagure_hook.py @@ -0,0 +1 @@ +/does/not/exist \ No newline at end of file diff --git a/pagure/hooks/files/pagure_hook_requests.py b/pagure/hooks/files/pagure_hook_requests.py deleted file mode 100755 index 137449c..0000000 --- a/pagure/hooks/files/pagure_hook_requests.py +++ /dev/null @@ -1,98 +0,0 @@ -#!/usr/bin/env python - - -"""Pagure specific hook to update pull-requests stored in the database -based on the information pushed in the requests git repository. -""" - -from __future__ import print_function, unicode_literals - -import os -import sys - - -# We need to access the database -if "PAGURE_CONFIG" not in os.environ and os.path.exists( - "/etc/pagure/pagure.cfg" -): - os.environ["PAGURE_CONFIG"] = "/etc/pagure/pagure.cfg" - - -import pagure.config # noqa: E402 -import pagure.lib.tasks_services # noqa: E402 - - -_config = pagure.config.config -abspath = os.path.abspath(os.environ["GIT_DIR"]) - - -def get_files_to_load(new_commits_list): - - print("Files changed by new commits:\n") - file_list = [] - new_commits_list.reverse() - for commit in new_commits_list: - filenames = pagure.lib.git.read_git_lines( - ["diff-tree", "--no-commit-id", "--name-only", "-r", commit], - abspath, - ) - for line in filenames: - if line.strip(): - file_list.append(line.strip()) - - return file_list - - -def run_as_post_receive_hook(): - - repo = pagure.lib.git.get_repo_name(abspath) - username = pagure.lib.git.get_username(abspath) - namespace = pagure.lib.git.get_repo_namespace( - abspath, gitfolder=_config["TICKETS_FOLDER"] - ) - if _config.get("HOOK_DEBUG", False): - print("repo:", repo) - print("user:", username) - print("namespace:", namespace) - - for line in sys.stdin: - if _config.get("HOOK_DEBUG", False): - print(line) - (oldrev, newrev, refname) = line.strip().split(" ", 2) - - if _config.get("HOOK_DEBUG", False): - print(" -- Old rev") - print(oldrev) - print(" -- New rev") - print(newrev) - print(" -- Ref name") - print(refname) - - if set(newrev) == set(["0"]): - print( - "Deleting a reference/branch, so we won't run the " - "pagure hook" - ) - return - - commits = pagure.lib.git.get_revs_between( - oldrev, newrev, abspath, refname - ) - - pagure.lib.tasks_services.load_json_commits_to_db.delay( - name=repo, - commits=commits, - abspath=abspath, - data_type="pull-request", - agent=os.environ.get("GL_USER"), - namespace=namespace, - username=username, - ) - - -def main(args): - run_as_post_receive_hook() - - -if __name__ == "__main__": - main(sys.argv[1:]) diff --git a/pagure/hooks/files/pagure_hook_requests.py b/pagure/hooks/files/pagure_hook_requests.py new file mode 120000 index 0000000..6be2006 --- /dev/null +++ b/pagure/hooks/files/pagure_hook_requests.py @@ -0,0 +1 @@ +/does/not/exist \ No newline at end of file diff --git a/pagure/hooks/files/pagure_hook_tickets.py b/pagure/hooks/files/pagure_hook_tickets.py deleted file mode 100755 index c9577b2..0000000 --- a/pagure/hooks/files/pagure_hook_tickets.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python - - -"""Pagure specific hook to update tickets stored in the database based on -the information pushed in the tickets git repository. -""" -from __future__ import print_function, unicode_literals - -import os -import sys - - -# We need to access the database -if "PAGURE_CONFIG" not in os.environ and os.path.exists( - "/etc/pagure/pagure.cfg" -): - os.environ["PAGURE_CONFIG"] = "/etc/pagure/pagure.cfg" - -import pagure.config # noqa: E402 -import pagure.lib.tasks_services # noqa: E402 - - -_config = pagure.config.config -abspath = os.path.abspath(os.environ["GIT_DIR"]) - - -def run_as_post_receive_hook(): - - repo = pagure.lib.git.get_repo_name(abspath) - username = pagure.lib.git.get_username(abspath) - namespace = pagure.lib.git.get_repo_namespace( - abspath, gitfolder=_config["TICKETS_FOLDER"] - ) - if _config.get("HOOK_DEBUG", False): - print("repo:", repo) - print("user:", username) - print("namespace:", namespace) - - for line in sys.stdin: - if _config.get("HOOK_DEBUG", False): - print(line) - (oldrev, newrev, refname) = line.strip().split(" ", 2) - - if _config.get("HOOK_DEBUG", False): - print(" -- Old rev") - print(oldrev) - print(" -- New rev") - print(newrev) - print(" -- Ref name") - print(refname) - - if set(newrev) == set(["0"]): - print( - "Deleting a reference/branch, so we won't run the " - "pagure hook" - ) - return - - commits = pagure.lib.git.get_revs_between( - oldrev, newrev, abspath, refname - ) - - pagure.lib.tasks_services.load_json_commits_to_db.delay( - name=repo, - commits=commits, - abspath=abspath, - data_type="ticket", - agent=os.environ.get("GL_USER"), - namespace=namespace, - username=username, - ) - - -def main(args): - run_as_post_receive_hook() - - -if __name__ == "__main__": - main(sys.argv[1:]) diff --git a/pagure/hooks/files/pagure_hook_tickets.py b/pagure/hooks/files/pagure_hook_tickets.py new file mode 120000 index 0000000..6be2006 --- /dev/null +++ b/pagure/hooks/files/pagure_hook_tickets.py @@ -0,0 +1 @@ +/does/not/exist \ No newline at end of file diff --git a/pagure/hooks/files/pagure_no_new_branches b/pagure/hooks/files/pagure_no_new_branches deleted file mode 100755 index 759c9c4..0000000 --- a/pagure/hooks/files/pagure_no_new_branches +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash -# adapted from https://stackoverflow.com/a/29880516 - -retcode=0 -while read -r old new refname; do - if [[ $refname == refs/heads/* && $old != *[^0]* ]]; then - retcode=1 - echo "Creating new branches is disabled on this project." - fi -done - -exit $retcode diff --git a/pagure/hooks/files/pagure_no_new_branches b/pagure/hooks/files/pagure_no_new_branches new file mode 120000 index 0000000..6be2006 --- /dev/null +++ b/pagure/hooks/files/pagure_no_new_branches @@ -0,0 +1 @@ +/does/not/exist \ No newline at end of file diff --git a/pagure/hooks/mirror_hook.py b/pagure/hooks/mirror_hook.py index 40dbeb7..f9fa672 100644 --- a/pagure/hooks/mirror_hook.py +++ b/pagure/hooks/mirror_hook.py @@ -19,12 +19,16 @@ except ImportError: from sqlalchemy.orm import relation from sqlalchemy.orm import backref +import pagure.config import pagure.lib.tasks_mirror -from pagure.hooks import BaseHook, RequiredIf +from pagure.hooks import BaseHook, BaseRunner, RequiredIf from pagure.lib.model import BASE, Project from pagure.utils import get_repo_path, ssh_urlpattern +_config = pagure.config.reload_config() + + class MirrorTable(BASE): """ Stores information about the mirroring hook deployed on a project. @@ -60,6 +64,30 @@ class MirrorTable(BASE): ) +class MirrorRunner(BaseRunner): + """ Runner for the mirror hook. """ + + @staticmethod + def post_receive(session, username, project, repotype, repodir, changes): + """ Run the default post-receive hook. + + For args, see BaseRunner.runhook. + """ + print("Running the default hook") + if repotype != "main": + if _config.get("HOOK_DEBUG", False): + print("Default hook only runs on the main project repository") + return + + pagure.lib.tasks_mirror.mirror_project.delay( + username=project.user.user if project.is_fork else None, + namespace=project.namespace, + name=project.name, + ) + + session.close() + + class CustomRegexp(wtforms.validators.Regexp): def __init__(self, *args, **kwargs): self.optional = kwargs.get("optional") or False @@ -120,6 +148,7 @@ class MirrorHook(BaseHook): backref = "mirror_hook" form_fields = ["active", "target", "public_key", "last_log"] form_fields_readonly = ["public_key", "last_log"] + runner = MirrorRunner @classmethod def install(cls, project, dbobj): diff --git a/pagure/hooks/pagure_ci.py b/pagure/hooks/pagure_ci.py index fbcc74a..4dc6f77 100644 --- a/pagure/hooks/pagure_ci.py +++ b/pagure/hooks/pagure_ci.py @@ -22,7 +22,7 @@ from sqlalchemy.orm import relation from sqlalchemy.orm import backref import pagure.lib -from pagure.hooks import BaseHook, RequiredIf +from pagure.hooks import BaseHook, BaseRunner, RequiredIf from pagure.lib.model import BASE, Project @@ -62,6 +62,15 @@ class PagureCITable(BASE): ) +class PagureCIRunner(BaseRunner): + """ Runner for the pagure-ci hook, it does nothing as the magic is part + of the CI system itself (to see if there was a commit made and build if + so). + """ + + pass + + tmpl = """ {% if repo | hasattr('ci_hook') and repo.ci_hook and repo.ci_hook.pagure_ci_token %} @@ -154,6 +163,7 @@ class PagureCi(BaseHook): db_object = PagureCITable backref = "ci_hook" form_fields = ["ci_type", "ci_url", "ci_job", "active_commit", "active_pr"] + runner = PagureCIRunner @classmethod def set_up(cls, project): diff --git a/pagure/hooks/pagure_force_commit.py b/pagure/hooks/pagure_force_commit.py index 6f80f13..3dc048e 100644 --- a/pagure/hooks/pagure_force_commit.py +++ b/pagure/hooks/pagure_force_commit.py @@ -10,8 +10,9 @@ from __future__ import unicode_literals +import sys + import sqlalchemy as sa -import pygit2 import wtforms try: @@ -21,9 +22,9 @@ except ImportError: from sqlalchemy.orm import relation from sqlalchemy.orm import backref -from pagure.hooks import BaseHook, RequiredIf +import pagure.lib.git +from pagure.hooks import BaseHook, BaseRunner, RequiredIf from pagure.lib.model import BASE, Project -from pagure.utils import get_repo_path class PagureForceCommitTable(BASE): @@ -60,6 +61,43 @@ class PagureForceCommitTable(BASE): ) +class PagureForceCommitRunner(BaseRunner): + """ Runner for the hook blocking force push. """ + + @staticmethod + def pre_receive(session, username, project, repotype, repodir, changes): + """ Run the pre-receive tasks of a hook. + + For args, see BaseRunner.runhook. + """ + + # Get the list of branches + branches = [] + if project.pagure_force_commit_hook: + branches = [ + branch.strip() + for branch in project.pagure_force_commit_hook.branches.split( + "," + ) + if branch.strip() + ] + + for refname in changes: + (oldrev, newrev) = changes[refname] + + refname = refname.replace("refs/heads/", "") + if refname in branches or branches == ["*"]: + + if set(newrev) == set(["0"]): + print("Deletion is forbidden") + session.close() + sys.exit(1) + elif pagure.lib.git.is_forced_push(oldrev, newrev, repodir): + print("Non fast-forward push are forbidden") + session.close() + sys.exit(1) + + class PagureForceCommitForm(FlaskForm): """ Form to configure the pagure hook. """ @@ -83,33 +121,4 @@ class PagureForceCommitHook(BaseHook): backref = "pagure_force_commit_hook" form_fields = ["branches", "active"] hook_type = "pre-receive" - - @classmethod - def install(cls, project, dbobj): - """ Method called to install the hook for a project. - - :arg project: a ``pagure.model.Project`` object to which the hook - should be installed - - """ - # Init the git repo in case - repopaths = [get_repo_path(project)] - pygit2.Repository(repopaths[0]) - - cls.base_install( - repopaths, - dbobj, - "pagureforcecommit", - "pagure_force_commit_hook.py", - ) - - @classmethod - def remove(cls, project): - """ Method called to remove the hook of a project. - - :arg project: a ``pagure.model.Project`` object to which the hook - should be installed - - """ - repopaths = [get_repo_path(project)] - cls.base_remove(repopaths, "pagureforcecommit") + runner = PagureForceCommitRunner diff --git a/pagure/hooks/pagure_hook.py b/pagure/hooks/pagure_hook.py index f536029..f2f9b89 100644 --- a/pagure/hooks/pagure_hook.py +++ b/pagure/hooks/pagure_hook.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- """ - (c) 2014-2016 - Copyright Red Hat Inc + (c) 2014-2018 - Copyright Red Hat Inc Authors: Pierre-Yves Chibon @@ -10,8 +10,9 @@ from __future__ import unicode_literals -import os +import logging +import pygit2 import sqlalchemy as sa import wtforms @@ -19,13 +20,18 @@ try: from flask_wtf import FlaskForm except ImportError: from flask_wtf import Form as FlaskForm +from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm import relation from sqlalchemy.orm import backref -from pagure.config import config as pagure_config -from pagure.hooks import BaseHook +import pagure.config +import pagure.lib.git +from pagure.hooks import BaseHook, BaseRunner from pagure.lib.model import BASE, Project -from pagure.utils import get_repo_path + + +_log = logging.getLogger(__name__) +pagure_config = pagure.config.reload_config() class PagureTable(BASE): @@ -59,6 +65,198 @@ class PagureTable(BASE): ) +def generate_revision_change_log( + session, project, username, repodir, new_commits_list +): + + print("Detailed log of new commits:\n\n") + commitid = None + for line in pagure.lib.git.read_git_lines( + ["log", "--no-walk"] + new_commits_list + ["--"], repodir + ): + if line.startswith("commit"): + commitid = line.split("commit ")[-1] + + line = line.strip() + print("*", line) + for issue_or_pr in pagure.lib.link.get_relation( + session, + project.name, + project.username if project.is_fork else None, + project.namespace, + line, + "fixes", + include_prs=True, + ): + if pagure_config.get("HOOK_DEBUG", False): + print(commitid, relation) + fixes_relation( + session, + username, + commitid, + issue_or_pr, + pagure_config.get("APP_URL"), + ) + + for issue in pagure.lib.link.get_relation( + session, + project.name, + project.username if project.is_fork else None, + project.namespace, + line, + "relates", + ): + if pagure_config.get("HOOK_DEBUG", False): + print(commitid, issue) + relates_commit( + session, + username, + commitid, + issue, + pagure_config.get("APP_URL"), + ) + + +def relates_commit(session, username, commitid, issue, app_url=None): + """ Add a comment to an issue that this commit relates to it. """ + + url = "../%s" % commitid[:8] + if app_url: + if app_url.endswith("/"): + app_url = app_url[:-1] + project = issue.project.fullname + if issue.project.is_fork: + project = "fork/%s" % project + url = "%s/%s/c/%s" % (app_url, project, commitid[:8]) + + comment = """ Commit [%s](%s) relates to this ticket""" % ( + commitid[:8], + url, + ) + + try: + pagure.lib.add_issue_comment( + session, issue=issue, comment=comment, user=username + ) + session.commit() + except pagure.exceptions.PagureException as err: + print(err) + except SQLAlchemyError as err: # pragma: no cover + session.rollback() + _log.exception(err) + + +def fixes_relation(session, username, commitid, relation, app_url=None): + """ Add a comment to an issue or PR that this commit fixes it and update + the status if the commit is in the master branch. """ + + url = "../c/%s" % commitid[:8] + if app_url: + if app_url.endswith("/"): + app_url = app_url[:-1] + project = relation.project.fullname + if relation.project.is_fork: + project = "fork/%s" % project + url = "%s/%s/c/%s" % (app_url, project, commitid[:8]) + + comment = """ Commit [%s](%s) fixes this %s""" % ( + commitid[:8], + url, + relation.isa, + ) + + try: + if relation.isa == "issue": + pagure.lib.add_issue_comment( + session, issue=relation, comment=comment, user=username + ) + elif relation.isa == "pull-request": + pagure.lib.add_pull_request_comment( + session, + request=relation, + commit=None, + tree_id=None, + filename=None, + row=None, + comment=comment, + user=username, + ) + session.commit() + except pagure.exceptions.PagureException as err: + print(err) + except SQLAlchemyError as err: # pragma: no cover + session.rollback() + _log.exception(err) + + try: + if relation.isa == "issue": + pagure.lib.edit_issue( + session, + relation, + user=username, + status="Closed", + close_status="Fixed", + ) + elif relation.isa == "pull-request": + pagure.lib.close_pull_request( + session, relation, user=username, merged=True + ) + session.commit() + except pagure.exceptions.PagureException as err: + print(err) + except SQLAlchemyError as err: # pragma: no cover + session.rollback() + print("ERROR", err) + _log.exception(err) + + +class PagureRunner(BaseRunner): + """ Runner for the pagure's specific git hook. """ + + @staticmethod + def post_receive(session, username, project, repotype, repodir, changes): + """ Run the default post-receive hook. + + For args, see BaseRunner.runhook. + """ + + if repotype != "main": + print("The pagure hook only runs on the main git repo.") + return + + for refname in changes: + (oldrev, newrev) = changes[refname] + + # Retrieve the default branch + repo_obj = pygit2.Repository(repodir) + default_branch = None + if not repo_obj.is_empty and not repo_obj.head_is_unborn: + default_branch = repo_obj.head.shorthand + + # Skip all branch but the default one + refname = refname.replace("refs/heads/", "") + if refname != default_branch: + continue + + if set(newrev) == set(["0"]): + print( + "Deleting a reference/branch, so we won't run the " + "pagure hook" + ) + return + + generate_revision_change_log( + session, + project, + username, + repodir, + pagure.lib.git.get_revs_between( + oldrev, newrev, repodir, refname + ), + ) + session.close() + + class PagureForm(FlaskForm): """ Form to configure the pagure hook. """ @@ -109,39 +307,4 @@ class PagureHook(BaseHook): db_object = PagureTable backref = "pagure_hook" form_fields = ["active"] - - @classmethod - def install(cls, project, dbobj): - """ Method called to install the hook for a project. - - :arg project: a ``pagure.model.Project`` object to which the hook - should be installed - - """ - repopaths = [get_repo_path(project)] - for folder in [ - pagure_config.get("DOCS_FOLDER"), - pagure_config.get("REQUESTS_FOLDER"), - ]: - if folder: - repopaths.append(os.path.join(folder, project.path)) - - cls.base_install(repopaths, dbobj, "pagure", "pagure_hook.py") - - @classmethod - def remove(cls, project): - """ Method called to remove the hook of a project. - - :arg project: a ``pagure.model.Project`` object to which the hook - should be installed - - """ - repopaths = [get_repo_path(project)] - for folder in [ - pagure_config.get("DOCS_FOLDER"), - pagure_config.get("REQUESTS_FOLDER"), - ]: - if folder: - repopaths.append(os.path.join(folder, project.path)) - - cls.base_remove(repopaths, "pagure") + runner = PagureRunner diff --git a/pagure/hooks/pagure_no_new_branches.py b/pagure/hooks/pagure_no_new_branches.py index e0b2e41..addcb63 100644 --- a/pagure/hooks/pagure_no_new_branches.py +++ b/pagure/hooks/pagure_no_new_branches.py @@ -9,6 +9,7 @@ """ from __future__ import unicode_literals +import sys import sqlalchemy as sa import wtforms @@ -20,9 +21,8 @@ except ImportError: from sqlalchemy.orm import relation from sqlalchemy.orm import backref -from pagure.hooks import BaseHook +from pagure.hooks import BaseHook, BaseRunner from pagure.lib.model import BASE, Project -from pagure.utils import get_repo_path class PagureNoNewBranchesTable(BASE): @@ -56,6 +56,27 @@ class PagureNoNewBranchesTable(BASE): ) +class PagureNoNewBranchRunner(BaseRunner): + """ Runner for the hook blocking new branches from being created. """ + + @staticmethod + def pre_receive(session, username, project, repotype, repodir, changes): + """ Run the pre-receive tasks of a hook. + + For args, see BaseRunner.runhook. + """ + + for refname in changes: + (oldrev, newrev) = changes[refname] + + if set(oldrev) == set(["0"]): + print( + "Creating a new reference/branch is not allowed in this" + " project." + ) + sys.exit(1) + + class PagureNoNewBranchesForm(FlaskForm): """ Form to configure the pagure hook. """ @@ -72,32 +93,4 @@ class PagureNoNewBranchesHook(BaseHook): backref = "pagure_hook_no_new_branches" form_fields = ["active"] hook_type = "pre-receive" - - @classmethod - def install(cls, project, dbobj): - """ Method called to install the hook for a project. - - :arg project: a ``pagure.model.Project`` object to which the hook - should be installed - - """ - repopaths = [get_repo_path(project)] - - cls.base_install( - repopaths, - dbobj, - "pagure_no_new_branches", - "pagure_no_new_branches", - ) - - @classmethod - def remove(cls, project): - """ Method called to remove the hook of a project. - - :arg project: a ``pagure.model.Project`` object to which the hook - should be installed - - """ - repopaths = [get_repo_path(project)] - - cls.base_remove(repopaths, "pagure_no_new_branches") + runner = PagureNoNewBranchRunner diff --git a/pagure/hooks/pagure_request_hook.py b/pagure/hooks/pagure_request_hook.py index 7242eeb..4a8a05d 100644 --- a/pagure/hooks/pagure_request_hook.py +++ b/pagure/hooks/pagure_request_hook.py @@ -10,9 +10,6 @@ from __future__ import unicode_literals -import os - -import flask import sqlalchemy as sa import wtforms @@ -23,8 +20,8 @@ except ImportError: from sqlalchemy.orm import relation from sqlalchemy.orm import backref -from pagure.config import config as pagure_config -from pagure.hooks import BaseHook +import pagure.lib.git +from pagure.hooks import BaseHook, BaseRunner from pagure.lib.model import BASE, Project @@ -60,6 +57,50 @@ class PagureRequestsTable(BASE): ) +class PagureRequestRunner(BaseRunner): + """ Runner for the hook updating the db about requests on push to the + git repo containing the meta-data about pull-requests. + """ + + @staticmethod + def post_receive(session, username, project, repotype, repodir, changes): + """ Run the default post-receive hook. + + For args, see BaseRunner.runhook. + """ + + if repotype != "requests": + print( + "The pagure requests hook only runs on the requests " + "git repo." + ) + return + + for refname in changes: + (oldrev, newrev) = changes[refname] + + if set(newrev) == set(["0"]): + print( + "Deleting a reference/branch, so we won't run the " + "pagure hook" + ) + return + + commits = pagure.lib.git.get_revs_between( + oldrev, newrev, repodir, refname + ) + + pagure.lib.tasks_services.load_json_commits_to_db.delay( + name=project.name, + commits=commits, + abspath=repodir, + data_type="pull-request", + agent=username, + namespace=project.namespace, + username=project.user.user if project.is_fork else None, + ) + + class PagureRequestsForm(FlaskForm): """ Form to configure the pagure hook. """ @@ -79,57 +120,4 @@ class PagureRequestHook(BaseHook): db_object = PagureRequestsTable backref = "pagure_hook_requests" form_fields = ["active"] - - @classmethod - def set_up(cls, project): - """ Install the generic post-receive hook that allow us to call - multiple post-receive hooks as set per plugin. - """ - repopath = os.path.join(pagure_config["REQUESTS_FOLDER"], project.path) - if not os.path.exists(repopath): - flask.abort(404, "No git repo found") - - hook_files = os.path.join( - os.path.dirname(os.path.realpath(__file__)), "files" - ) - - # Make sure the hooks folder exists - hookfolder = os.path.join(repopath, "hooks") - if not os.path.exists(hookfolder): - os.makedirs(hookfolder) - - # Install the main post-receive file - postreceive = os.path.join(hookfolder, "post-receive") - hook_file = os.path.join(hook_files, "post-receive") - if not os.path.exists(postreceive): - os.symlink(hook_file, postreceive) - - @classmethod - def install(cls, project, dbobj): - """ Method called to install the hook for a project. - - :arg project: a ``pagure.model.Project`` object to which the hook - should be installed - - """ - repopaths = [ - os.path.join(pagure_config["REQUESTS_FOLDER"], project.path) - ] - - cls.base_install( - repopaths, dbobj, "pagure-requests", "pagure_hook_requests.py" - ) - - @classmethod - def remove(cls, project): - """ Method called to remove the hook of a project. - - :arg project: a ``pagure.model.Project`` object to which the hook - should be installed - - """ - repopaths = [ - os.path.join(pagure_config["REQUESTS_FOLDER"], project.path) - ] - - cls.base_remove(repopaths, "pagure-requests") + runner = PagureRequestRunner diff --git a/pagure/hooks/pagure_ticket_hook.py b/pagure/hooks/pagure_ticket_hook.py index 8e30ad8..dddf7fb 100644 --- a/pagure/hooks/pagure_ticket_hook.py +++ b/pagure/hooks/pagure_ticket_hook.py @@ -23,8 +23,9 @@ except ImportError: from sqlalchemy.orm import relation from sqlalchemy.orm import backref +import pagure.lib from pagure.config import config as pagure_config -from pagure.hooks import BaseHook +from pagure.hooks import BaseHook, BaseRunner from pagure.lib.model import BASE, Project @@ -59,6 +60,45 @@ class PagureTicketsTable(BASE): ) +class PagureTicketRunner(BaseRunner): + """ Runner for the git hook updating the DB of tickets on push. """ + + @staticmethod + def pre_receive(session, username, project, repotype, repodir, changes): + """ Run the pre-receive tasks of a hook. + + For args, see BaseRunner.runhook. + """ + + if repotype != "tickets": + print("The ticket hook only runs on the ticket git repository.") + return + + for refname in changes: + (oldrev, newrev) = changes[refname] + + if set(newrev) == set(["0"]): + print( + "Deleting a reference/branch, so we won't run the " + "pagure hook" + ) + return + + commits = pagure.lib.git.get_revs_between( + oldrev, newrev, repodir, refname + ) + + pagure.lib.tasks_services.load_json_commits_to_db.delay( + name=project.name, + commits=commits, + abspath=repodir, + data_type="ticket", + agent=username, + namespace=project.namespace, + username=project.user.user if project.is_fork else None, + ) + + class PagureTicketsForm(FlaskForm): """ Form to configure the pagure hook. """ @@ -78,6 +118,7 @@ class PagureTicketHook(BaseHook): db_object = PagureTicketsTable backref = "pagure_hook_tickets" form_fields = ["active"] + runner = PagureTicketRunner @classmethod def set_up(cls, project): diff --git a/pagure/hooks/pagure_unsigned_commits.py b/pagure/hooks/pagure_unsigned_commits.py index 56d80c4..15d842e 100644 --- a/pagure/hooks/pagure_unsigned_commits.py +++ b/pagure/hooks/pagure_unsigned_commits.py @@ -10,6 +10,8 @@ from __future__ import unicode_literals +import sys + import sqlalchemy as sa import wtforms @@ -20,9 +22,12 @@ except ImportError: from sqlalchemy.orm import relation from sqlalchemy.orm import backref -from pagure.hooks import BaseHook +import pagure.config +from pagure.hooks import BaseHook, BaseRunner from pagure.lib.model import BASE, Project -from pagure.utils import get_repo_path + + +_config = pagure.config.reload_config() class PagureUnsignedCommitTable(BASE): @@ -57,6 +62,46 @@ class PagureUnsignedCommitTable(BASE): ) +class PagureUnsignerRunner(BaseRunner): + """ Runner for the hook blocking unsigned commits. """ + + @staticmethod + def pre_receive(session, username, project, repotype, repodir, changes): + """ Run the pre-receive tasks of a hook. + + For args, see BaseRunner.runhook. + """ + + for refname in changes: + (oldrev, newrev) = changes[refname] + + if set(newrev) == set(["0"]): + print( + "Deleting a reference/branch, so we won't run the " + "hook to block unsigned commits" + ) + return + + commits = pagure.lib.git.get_revs_between( + oldrev, newrev, repodir, refname + ) + for commit in commits: + if _config.get("HOOK_DEBUG", False): + print("Processing commit: %s" % commit) + signed = False + for line in pagure.lib.git.read_git_lines( + ["log", "--no-walk", commit], repodir + ): + if line.lower().strip().startswith("signed-off-by"): + signed = True + break + if _config.get("HOOK_DEBUG", False): + print(" - Commit: %s is signed: %s" % (commit, signed)) + if not signed: + print("Commit %s is not signed" % commit) + sys.exit(1) + + class PagureUnsignedCommitForm(FlaskForm): """ Form to configure the pagure hook. """ @@ -76,32 +121,4 @@ class PagureUnsignedCommitHook(BaseHook): backref = "pagure_unsigned_commit_hook" form_fields = ["active"] hook_type = "pre-receive" - - @classmethod - def install(cls, project, dbobj): - """ Method called to install the hook for a project. - - :arg project: a ``pagure.model.Project`` object to which the hook - should be installed - - """ - repopaths = [get_repo_path(project)] - - cls.base_install( - repopaths, - dbobj, - "pagureunsignedcommit", - "pagure_block_unsigned.py", - ) - - @classmethod - def remove(cls, project): - """ Method called to remove the hook of a project. - - :arg project: a ``pagure.model.Project`` object to which the hook - should be installed - - """ - repopaths = [get_repo_path(project)] - - cls.base_remove(repopaths, "pagureunsignedcommit") + runner = PagureUnsignerRunner diff --git a/pagure/internal/__init__.py b/pagure/internal/__init__.py index ba562c9..28f5c7c 100644 --- a/pagure/internal/__init__.py +++ b/pagure/internal/__init__.py @@ -16,7 +16,6 @@ import collections import logging import os -import celery import flask import pygit2 @@ -227,18 +226,18 @@ def mergeable_request_pull(): ) except pygit2.GitError as err: response = flask.jsonify( - {"code": "CONFLICTS", "message": "%s" % err}) + {"code": "CONFLICTS", "message": "%s" % err} + ) response.status_code = 409 return response except pagure.exceptions.PagureException as err: response = flask.jsonify( - {"code": "CONFLICTS", "message": "%s" % err}) + {"code": "CONFLICTS", "message": "%s" % err} + ) response.status_code = 500 return response - return flask.jsonify( - pagure.utils.get_merge_options(request, merge_status) - ) + return flask.jsonify(pagure.utils.get_merge_options(request, merge_status)) @PV.route("/pull-request/ready", methods=["POST"]) @@ -297,17 +296,10 @@ def get_pull_request_ready_branch(): response.status_code = 400 return response task = pagure.lib.tasks.pull_request_ready_branch.delay( - namespace=args_namespace, - name=args_reponame, - user=args_user, + namespace=args_namespace, name=args_reponame, user=args_user ) - return flask.jsonify( - { - "code": "OK", - "task": task.id, - } - ) + return flask.jsonify({"code": "OK", "task": task.id}) @PV.route("//issue/template", methods=["POST"]) diff --git a/pagure/lib/model.py b/pagure/lib/model.py index 5aa0093..0759b96 100644 --- a/pagure/lib/model.py +++ b/pagure/lib/model.py @@ -2237,7 +2237,7 @@ class PullRequestFlag(BASE): backref=backref( "flags", order_by=str("(pull_request_flags.c.date_created).desc()"), - cascade="delete, delete-orphan" + cascade="delete, delete-orphan", ), foreign_keys=[pull_request_uid], remote_side=[PullRequest.uid], diff --git a/pagure/lib/plugins.py b/pagure/lib/plugins.py index 394f449..b3a4dd3 100644 --- a/pagure/lib/plugins.py +++ b/pagure/lib/plugins.py @@ -50,17 +50,22 @@ def get_plugin(plugin_name): return plugin -def get_enabled_plugins(project): +def get_enabled_plugins(project, with_default=False): """ Returns a list of plugins enabled for a specific project. Args: project (model.Project): The project to look for. + with_default (boolean): Wether or not the returned list should + include the default hook/plugin. Returns: (list): A list of tuples (pluginclass, dbobj) with the plugin classess and dbobjects for plugins enabled for the project. """ from pagure.hooks import BaseHook + from pagure.hooks.default import Default enabled = [] + if with_default: + enabled = [(Default(), None)] for plugin in load("pagure.hooks", subclasses=BaseHook): if plugin.db_object and hasattr(project, plugin.backref): dbobj = getattr(project, plugin.backref) diff --git a/pagure/lib/tasks_services.py b/pagure/lib/tasks_services.py index cafcc6a..3713c35 100644 --- a/pagure/lib/tasks_services.py +++ b/pagure/lib/tasks_services.py @@ -383,7 +383,8 @@ def load_json_commits_to_db( @conn.task(queue=pagure_config.get("CI_CELERY_QUEUE", None), bind=True) @pagure_task def trigger_ci_build( - self, session, cause, branch, ci_type, project_name=None, pr_uid=None): + self, session, cause, branch, ci_type, project_name=None, pr_uid=None +): """ Triggers a new run of the CI system on the specified pull-request. diff --git a/pagure/utils.py b/pagure/utils.py index 74e84e5..25165ca 100644 --- a/pagure/utils.py +++ b/pagure/utils.py @@ -526,12 +526,13 @@ def get_merge_options(request, merge_status): "code": "CONFLICTS", "short_code": "Conflicts", "message": "The pull-request must be rebased before merging", - } + }, } if merge_status == "MERGE": if request.project.settings.get( - "disable_non_fast-forward_merges", False): + "disable_non_fast-forward_merges", False + ): merge_status += "-non-ff-bad" else: merge_status += "-non-ff-ok" diff --git a/runtests.py b/runtests.py index ba79c48..6bdf8b9 100755 --- a/runtests.py +++ b/runtests.py @@ -28,6 +28,8 @@ PRINTLOCK = None RUNNING = [] FAILED = [] NUMPROCS = multiprocessing.cpu_count() - 1 +if os.environ.get('BUILD_ID'): + NUMPROCS = multiprocessing.cpu_count() def setup_parser(): diff --git a/tests/test_pagure_flask_api_pr_flag.py b/tests/test_pagure_flask_api_pr_flag.py index 1bf40af..b220ce0 100644 --- a/tests/test_pagure_flask_api_pr_flag.py +++ b/tests/test_pagure_flask_api_pr_flag.py @@ -484,10 +484,10 @@ class PagureFlaskApiPRFlagtests(tests.Modeltests): request = pagure.lib.search_pull_requests( self.session, project_id=1, requestid=1) self.assertEqual(len(request.flags), 2) - self.assertEqual(request.flags[0].comment, 'Tests passed') - self.assertEqual(request.flags[0].percent, 100) - self.assertEqual(request.flags[1].comment, 'Tests running again') - self.assertEqual(request.flags[1].percent, None) + self.assertEqual(request.flags[0].comment, 'Tests running again') + self.assertEqual(request.flags[0].percent, None) + self.assertEqual(request.flags[1].comment, 'Tests passed') + self.assertEqual(request.flags[1].percent, 100) @patch.dict('pagure.config.config', { diff --git a/tests/test_pagure_flask_internal.py b/tests/test_pagure_flask_internal.py index 47fb632..c6ab1d5 100644 --- a/tests/test_pagure_flask_internal.py +++ b/tests/test_pagure_flask_internal.py @@ -36,6 +36,8 @@ from pagure.lib.repo import PagureRepo class PagureFlaskInternaltests(tests.Modeltests): """ Tests for flask Internal controller of pagure """ + maxDiff = None + def setUp(self): """ Set up the environnment, ran before every tests. """ super(PagureFlaskInternaltests, self).setUp() @@ -2382,12 +2384,9 @@ class PagureFlaskInternaltests(tests.Modeltests): js_data = json.loads(output.get_data(as_text=True)) self.assertEqual( sorted(js_data.keys()), - ['code', 'message'] + ['code', 'task'] ) self.assertEqual(js_data['code'], 'OK') - self.assertEqual( - js_data['message'], - {'branch_w_pr': {}, 'new_branch': {}}) def test_get_pull_request_ready_branch_on_fork(self): '''Test the get_pull_request_ready_branch from the internal API on @@ -2433,18 +2432,19 @@ class PagureFlaskInternaltests(tests.Modeltests): js_data = json.loads(output.get_data(as_text=True)) self.assertEqual( sorted(js_data.keys()), - ['code', 'message'] + ['code', 'task'] ) self.assertEqual(js_data['code'], 'OK') - self.assertListEqual( - sorted(js_data['message'].keys()), - ['branch_w_pr', 'new_branch']) - self.assertEqual(js_data['message']['branch_w_pr'], {}) - self.assertListEqual( - list(js_data['message']['new_branch']), ['feature']) - self.assertEqual(js_data['message']['new_branch']['feature']['commits'], 2) + output = self.app.get('/pv/task/' + js_data['task']) + self.assertEqual(output.status_code, 200) + js_data = json.loads(output.get_data(as_text=True)) self.assertEqual( - js_data['message']['new_branch']['feature']['target_branch'], 'master') + js_data, + {'results': { + 'branch_w_pr': {}, + 'new_branch': {'feature': + {'commits': 2, 'target_branch': 'master'}}}} + ) def test_get_pull_request_ready_branch_on_fork_no_parent_no_pr(self): '''Test the get_pull_request_ready_branch from the internal API on @@ -2561,18 +2561,19 @@ class PagureFlaskInternaltests(tests.Modeltests): js_data = json.loads(output.get_data(as_text=True)) self.assertEqual( sorted(js_data.keys()), - ['code', 'message'] + ['code', 'task'] ) self.assertEqual(js_data['code'], 'OK') + output = self.app.get('/pv/task/' + js_data['task']) + self.assertEqual(output.status_code, 200) + js_data = json.loads(output.get_data(as_text=True)) self.assertEqual( - sorted(js_data['message'].keys()), - ['branch_w_pr', 'new_branch']) - self.assertEqual(js_data['message']['branch_w_pr'], {}) - self.assertListEqual( - list(js_data['message']['new_branch']), ['feature']) - self.assertEqual(js_data['message']['new_branch']['feature']['commits'], 2) - self.assertEqual( - js_data['message']['new_branch']['feature']['target_branch'], 'master') + js_data, + {'results': { + 'branch_w_pr': {}, + 'new_branch': {'feature': + {'commits': 2, 'target_branch': 'master'}}}} + ) def test_get_pull_request_ready_branch_matching_target_off(self): '''Test the get_pull_request_ready_branch from the internal API on @@ -2625,18 +2626,19 @@ class PagureFlaskInternaltests(tests.Modeltests): js_data = json.loads(output.get_data(as_text=True)) self.assertEqual( sorted(js_data.keys()), - ['code', 'message'] + ['code', 'task'] ) self.assertEqual(js_data['code'], 'OK') - self.assertListEqual( - sorted(js_data['message'].keys()), - ['branch_w_pr', 'new_branch']) - self.assertEqual(js_data['message']['branch_w_pr'], {}) - self.assertListEqual( - list(js_data['message']['new_branch']), ['feature']) - self.assertEqual(js_data['message']['new_branch']['feature']['commits'], 2) + output = self.app.get('/pv/task/' + js_data['task']) + self.assertEqual(output.status_code, 200) + js_data = json.loads(output.get_data(as_text=True)) self.assertEqual( - js_data['message']['new_branch']['feature']['target_branch'], 'master') + js_data, + {'results': { + 'branch_w_pr': {}, + 'new_branch': {'feature': + {'commits': 2, 'target_branch': 'master'}}}} + ) @patch.dict('pagure.config.config', {'PR_TARGET_MATCHING_BRANCH': True}) def test_get_pull_request_ready_branch_matching_target_on(self): @@ -2690,18 +2692,19 @@ class PagureFlaskInternaltests(tests.Modeltests): js_data = json.loads(output.get_data(as_text=True)) self.assertEqual( sorted(js_data.keys()), - ['code', 'message'] + ['code', 'task'] ) self.assertEqual(js_data['code'], 'OK') - self.assertListEqual( - sorted(js_data['message'].keys()), - ['branch_w_pr', 'new_branch']) - self.assertEqual(js_data['message']['branch_w_pr'], {}) - self.assertListEqual( - list(js_data['message']['new_branch']), ['feature']) - self.assertEqual(js_data['message']['new_branch']['feature']['commits'], 1) + output = self.app.get('/pv/task/' + js_data['task']) + self.assertEqual(output.status_code, 200) + js_data = json.loads(output.get_data(as_text=True)) self.assertEqual( - js_data['message']['new_branch']['feature']['target_branch'], 'feature') + js_data, + {'results': { + 'branch_w_pr': {}, + 'new_branch': {'feature': + {'commits': 1, 'target_branch': 'feature'}}}} + ) def test_task_info_task_running(self): """ Test the task_info internal API endpoint when the task isn't diff --git a/tests/test_pagure_flask_ui_fork.py b/tests/test_pagure_flask_ui_fork.py index 59ce138..63656ad 100644 --- a/tests/test_pagure_flask_ui_fork.py +++ b/tests/test_pagure_flask_ui_fork.py @@ -3115,18 +3115,8 @@ index 0000000..2a552bb ) self.assertEqual(output.status_code, 200) data = json.loads(output.get_data(as_text=True)) - self.assertEqual( - data, - { - "code": "OK", - "message": { - "branch_w_pr": { - "feature": "test/pull-request/1" - }, - "new_branch": {} - } - } - ) + self.assertEqual(sorted(data.keys()), ['code', 'task']) + self.assertEqual(data['code'], 'OK') @patch('pagure.lib.notify.send_email') def test_fork_edit_file(self, send_email): diff --git a/tests/test_pagure_flask_ui_plugins_default_hook.py b/tests/test_pagure_flask_ui_plugins_default_hook.py index 2320f53..cd9389a 100644 --- a/tests/test_pagure_flask_ui_plugins_default_hook.py +++ b/tests/test_pagure_flask_ui_plugins_default_hook.py @@ -70,8 +70,6 @@ class PagureFlaskPluginDefaultHooktests(tests.Modeltests): 'namespace': None}) self.assertTrue(os.path.exists(os.path.join( - self.path, 'repos', 'test.git', 'hooks', 'post-receive.default'))) - self.assertTrue(os.path.exists(os.path.join( self.path, 'repos', 'test.git', 'hooks', 'post-receive'))) def test_plugin_default_remove(self): diff --git a/tests/test_pagure_flask_ui_plugins_mirror.py b/tests/test_pagure_flask_ui_plugins_mirror.py index eb781b8..137a803 100644 --- a/tests/test_pagure_flask_ui_plugins_mirror.py +++ b/tests/test_pagure_flask_ui_plugins_mirror.py @@ -190,9 +190,6 @@ class PagureFlaskPluginMirrortests(tests.Modeltests): self.assertTrue(os.path.exists(os.path.join( self.path, 'repos', 'test.git', 'hooks', - 'post-receive.mirror'))) - self.assertTrue(os.path.exists(os.path.join( - self.path, 'repos', 'test.git', 'hooks', 'post-receive'))) def test_plugin_mirror_deactivate(self): diff --git a/tests/test_pagure_flask_ui_plugins_noff.py b/tests/test_pagure_flask_ui_plugins_noff.py index 8de5a2c..6b89071 100644 --- a/tests/test_pagure_flask_ui_plugins_noff.py +++ b/tests/test_pagure_flask_ui_plugins_noff.py @@ -182,10 +182,6 @@ class PagureFlaskPluginNoFFtests(tests.SimplePagureTest): '', output_text) - self.assertTrue(os.path.exists(os.path.join( - self.path, 'repos', 'test.git', 'hooks', - 'pre-receive.pagureforcecommit'))) - # De-Activate hook data = {'csrf_token': csrf_token} output = self.app.post( diff --git a/tests/test_pagure_flask_ui_plugins_pagure_hook.py b/tests/test_pagure_flask_ui_plugins_pagure_hook.py index efd341d..a3e7536 100644 --- a/tests/test_pagure_flask_ui_plugins_pagure_hook.py +++ b/tests/test_pagure_flask_ui_plugins_pagure_hook.py @@ -166,9 +166,6 @@ class PagureFlaskPluginPagureHooktests(tests.SimplePagureTest): self.assertTrue(os.path.exists(os.path.join( self.path, 'repos', 'test.git', 'hooks', - 'post-receive.pagure'))) - self.assertTrue(os.path.exists(os.path.join( - self.path, 'repos', 'test.git', 'hooks', 'post-receive'))) self.assertTrue(os.path.exists(os.path.join( self.path, 'repos', 'docs', 'test.git', 'hooks', @@ -241,9 +238,6 @@ class PagureFlaskPluginPagureHooktests(tests.SimplePagureTest): self.assertTrue(os.path.exists(os.path.join( self.path, 'repos', 'test.git', 'hooks', - 'post-receive.pagure'))) - self.assertTrue(os.path.exists(os.path.join( - self.path, 'repos', 'test.git', 'hooks', 'post-receive'))) self.assertFalse(os.path.exists(os.path.join( self.path, 'docs', 'test.git', 'hooks', @@ -279,9 +273,6 @@ class PagureFlaskPluginPagureHooktests(tests.SimplePagureTest): self.assertTrue(os.path.exists(os.path.join( self.path, 'repos', 'test.git', 'hooks', - 'post-receive.pagure'))) - self.assertTrue(os.path.exists(os.path.join( - self.path, 'repos', 'test.git', 'hooks', 'post-receive'))) self.assertFalse(os.path.exists(os.path.join( self.path, 'docs', 'test.git', 'hooks', diff --git a/tests/test_pagure_flask_ui_plugins_pagure_no_new_branch.py b/tests/test_pagure_flask_ui_plugins_pagure_no_new_branch.py index be385d7..328cf34 100644 --- a/tests/test_pagure_flask_ui_plugins_pagure_no_new_branch.py +++ b/tests/test_pagure_flask_ui_plugins_pagure_no_new_branch.py @@ -137,10 +137,6 @@ class PagureFlaskPluginPagureNoNewBranchHooktests(tests.SimplePagureTest): '', output_text) - self.assertTrue(os.path.exists(os.path.join( - self.path, 'repos', 'test.git', 'hooks', - 'pre-receive.pagure_no_new_branches'))) - # De-Activate hook data = {'csrf_token': self.csrf_token} output = self.app.post( diff --git a/tests/test_pagure_flask_ui_plugins_pagure_request_hook.py b/tests/test_pagure_flask_ui_plugins_pagure_request_hook.py index ba5291f..c4d039d 100644 --- a/tests/test_pagure_flask_ui_plugins_pagure_request_hook.py +++ b/tests/test_pagure_flask_ui_plugins_pagure_request_hook.py @@ -119,10 +119,6 @@ class PagureFlaskPluginPagureRequestHooktests(tests.SimplePagureTest): '', output_text) - self.assertTrue(os.path.exists(os.path.join( - self.path, 'repos', 'requests', 'test.git', 'hooks', - 'post-receive.pagure-requests'))) - # De-Activate hook data = {'csrf_token': csrf_token} output = self.app.post( @@ -151,16 +147,6 @@ class PagureFlaskPluginPagureRequestHooktests(tests.SimplePagureTest): self.path, 'requests', 'test.git', 'hooks', 'post-receive.pagure-requests'))) - # Try re-activate hook w/o the git repo - data = { - 'csrf_token': csrf_token, - 'active': 'y', - } - shutil.rmtree(os.path.join(self.path, 'repos', 'requests', 'test.git')) - - output = self.app.post('/test/settings/Pagure requests', data=data) - self.assertEqual(output.status_code, 404) - if __name__ == '__main__': unittest.main(verbosity=2) diff --git a/tests/test_pagure_flask_ui_plugins_pagure_ticket_hook.py b/tests/test_pagure_flask_ui_plugins_pagure_ticket_hook.py index c773466..9ef5e8b 100644 --- a/tests/test_pagure_flask_ui_plugins_pagure_ticket_hook.py +++ b/tests/test_pagure_flask_ui_plugins_pagure_ticket_hook.py @@ -120,10 +120,6 @@ class PagureFlaskPluginPagureTicketHooktests(tests.SimplePagureTest): '', output_text) - self.assertTrue(os.path.exists(os.path.join( - self.path, 'repos', 'tickets', 'test.git', 'hooks', - 'post-receive.pagure-ticket'))) - # De-Activate hook data = {'csrf_token': csrf_token} output = self.app.post( diff --git a/tests/test_pagure_flask_ui_plugins_unsigned.py b/tests/test_pagure_flask_ui_plugins_unsigned.py index d786ec8..c95f3b1 100644 --- a/tests/test_pagure_flask_ui_plugins_unsigned.py +++ b/tests/test_pagure_flask_ui_plugins_unsigned.py @@ -107,10 +107,6 @@ class PagureFlaskPluginUnsignedtests(tests.SimplePagureTest): 'Hook activated', output_text) - self.assertTrue(os.path.exists(os.path.join( - self.path, 'repos', 'test.git', 'hooks', - 'pre-receive.pagureunsignedcommit'))) - # De-Activate hook data = {'csrf_token': csrf_token} output = self.app.post(