core: run ruff format

This commit is contained in:
RhodeCode Admin 2025-01-13 17:47:37 +01:00
parent 7130effb58
commit 166db21812
821 changed files with 82905 additions and 84121 deletions

View file

@ -30,21 +30,15 @@ log = logging.getLogger(__name__)
# includeme level later to allow per instance integration setup
integration_type_registry = IntegrationTypeRegistry()
integration_type_registry.register_integration_type(
webhook.WebhookIntegrationType)
integration_type_registry.register_integration_type(
slack.SlackIntegrationType)
integration_type_registry.register_integration_type(
email.EmailIntegrationType)
integration_type_registry.register_integration_type(webhook.WebhookIntegrationType)
integration_type_registry.register_integration_type(slack.SlackIntegrationType)
integration_type_registry.register_integration_type(email.EmailIntegrationType)
# dummy EE integration to show users what we have in EE edition
integration_type_registry.register_integration_type(
base.EEIntegration('Jira Issues integration', 'jira'))
integration_type_registry.register_integration_type(
base.EEIntegration('Redmine Tracker integration', 'redmine'))
integration_type_registry.register_integration_type(
base.EEIntegration('Jenkins CI integration', 'jenkins'))
integration_type_registry.register_integration_type(base.EEIntegration("Jira Issues integration", "jira"))
integration_type_registry.register_integration_type(base.EEIntegration("Redmine Tracker integration", "redmine"))
integration_type_registry.register_integration_type(base.EEIntegration("Jenkins CI integration", "jenkins"))
def integrations_event_handler(event):
@ -61,10 +55,8 @@ def integrations_event_handler(event):
except Exception:
exc_info = sys.exc_info()
store_exception(id(exc_info), exc_info)
log.exception(
'failure occurred when sending event %s to integration %s',
event, integration)
log.exception("failure occurred when sending event %s to integration %s", event, integration)
def includeme(config):
config.include('rhodecode.integrations.routes')
config.include("rhodecode.integrations.routes")

View file

@ -26,11 +26,10 @@ class IntegrationTypeRegistry(collections.OrderedDict):
"""
Registry Class to hold IntegrationTypes
"""
def register_integration_type(self, IntegrationType):
key = IntegrationType.key
if key in self:
log.debug(
'Overriding existing integration type %s (%s) with %s',
self[key].__class__, key, IntegrationType)
log.debug("Overriding existing integration type %s (%s) with %s", self[key].__class__, key, IntegrationType)
self[key] = IntegrationType

View file

@ -34,13 +34,13 @@ class ValidIntegrationPredicate(object):
self.val = val
def text(self):
return f'valid_integration_route = {self.val}'
return f"valid_integration_route = {self.val}"
phash = text
def __call__(self, info, request):
integration_type = info['match']['integration']
integration_id = info['match'].get('integration_id')
integration_type = info["match"]["integration"]
integration_id = info["match"].get("integration_id")
if integration_type not in integration_type_registry:
return False
@ -56,8 +56,8 @@ class ValidIntegrationPredicate(object):
return False
# match types to repo or repo group
repo_name = info['match'].get('repo_name')
repo_group_name = info['match'].get('repo_group_name')
repo_name = info["match"].get("repo_name")
repo_group_name = info["match"].get("repo_group_name")
repo, repo_group = None, None
if repo_name:
repo = Repository.get_by_repo_name(repo_name)
@ -78,164 +78,214 @@ class ValidIntegrationPredicate(object):
def includeme(config):
config.add_route_predicate(
'valid_integration', ValidIntegrationPredicate)
config.add_route_predicate("valid_integration", ValidIntegrationPredicate)
# global integrations
config.add_route('global_integrations_new',
ADMIN_PREFIX + '/integrations/new')
config.add_view(GlobalIntegrationsView,
attr='new_integration',
renderer='rhodecode:templates/admin/integrations/new.mako',
request_method='GET',
route_name='global_integrations_new')
config.add_route("global_integrations_new", ADMIN_PREFIX + "/integrations/new")
config.add_view(
GlobalIntegrationsView,
attr="new_integration",
renderer="rhodecode:templates/admin/integrations/new.mako",
request_method="GET",
route_name="global_integrations_new",
)
config.add_route('global_integrations_home',
ADMIN_PREFIX + '/integrations')
config.add_route('global_integrations_list',
ADMIN_PREFIX + '/integrations/{integration}')
for route_name in ['global_integrations_home', 'global_integrations_list']:
config.add_view(GlobalIntegrationsView,
attr='integration_list',
renderer='rhodecode:templates/admin/integrations/list.mako',
request_method='GET',
route_name=route_name)
config.add_route("global_integrations_home", ADMIN_PREFIX + "/integrations")
config.add_route("global_integrations_list", ADMIN_PREFIX + "/integrations/{integration}")
for route_name in ["global_integrations_home", "global_integrations_list"]:
config.add_view(
GlobalIntegrationsView,
attr="integration_list",
renderer="rhodecode:templates/admin/integrations/list.mako",
request_method="GET",
route_name=route_name,
)
config.add_route('global_integrations_create',
ADMIN_PREFIX + '/integrations/{integration}/new',
valid_integration=True)
config.add_route('global_integrations_edit',
ADMIN_PREFIX + '/integrations/{integration}/{integration_id}',
valid_integration=True)
config.add_route(
"global_integrations_create", ADMIN_PREFIX + "/integrations/{integration}/new", valid_integration=True
)
config.add_route(
"global_integrations_edit",
ADMIN_PREFIX + "/integrations/{integration}/{integration_id}",
valid_integration=True,
)
for route_name in ['global_integrations_create', 'global_integrations_edit']:
config.add_view(GlobalIntegrationsView,
attr='settings_get',
renderer='rhodecode:templates/admin/integrations/form.mako',
request_method='GET',
route_name=route_name)
config.add_view(GlobalIntegrationsView,
attr='settings_post',
renderer='rhodecode:templates/admin/integrations/form.mako',
request_method='POST',
route_name=route_name)
for route_name in ["global_integrations_create", "global_integrations_edit"]:
config.add_view(
GlobalIntegrationsView,
attr="settings_get",
renderer="rhodecode:templates/admin/integrations/form.mako",
request_method="GET",
route_name=route_name,
)
config.add_view(
GlobalIntegrationsView,
attr="settings_post",
renderer="rhodecode:templates/admin/integrations/form.mako",
request_method="POST",
route_name=route_name,
)
# repo group integrations
config.add_route('repo_group_integrations_home',
add_route_requirements('/{repo_group_name}/_settings/integrations'),
repo_group_route=True)
config.add_route(
"repo_group_integrations_home",
add_route_requirements("/{repo_group_name}/_settings/integrations"),
repo_group_route=True,
)
config.add_view(RepoGroupIntegrationsView,
attr='integration_list',
renderer='rhodecode:templates/admin/integrations/list.mako',
request_method='GET',
route_name='repo_group_integrations_home')
config.add_view(
RepoGroupIntegrationsView,
attr="integration_list",
renderer="rhodecode:templates/admin/integrations/list.mako",
request_method="GET",
route_name="repo_group_integrations_home",
)
config.add_route('repo_group_integrations_new',
add_route_requirements('/{repo_group_name}/_settings/integrations/new'),
repo_group_route=True)
config.add_view(RepoGroupIntegrationsView,
attr='new_integration',
renderer='rhodecode:templates/admin/integrations/new.mako',
request_method='GET',
route_name='repo_group_integrations_new')
config.add_route(
"repo_group_integrations_new",
add_route_requirements("/{repo_group_name}/_settings/integrations/new"),
repo_group_route=True,
)
config.add_view(
RepoGroupIntegrationsView,
attr="new_integration",
renderer="rhodecode:templates/admin/integrations/new.mako",
request_method="GET",
route_name="repo_group_integrations_new",
)
config.add_route('repo_group_integrations_list',
add_route_requirements('/{repo_group_name}/_settings/integrations/{integration}'),
repo_group_route=True,
valid_integration=True)
config.add_view(RepoGroupIntegrationsView,
attr='integration_list',
renderer='rhodecode:templates/admin/integrations/list.mako',
request_method='GET',
route_name='repo_group_integrations_list')
config.add_route(
"repo_group_integrations_list",
add_route_requirements("/{repo_group_name}/_settings/integrations/{integration}"),
repo_group_route=True,
valid_integration=True,
)
config.add_view(
RepoGroupIntegrationsView,
attr="integration_list",
renderer="rhodecode:templates/admin/integrations/list.mako",
request_method="GET",
route_name="repo_group_integrations_list",
)
config.add_route('repo_group_integrations_create',
add_route_requirements('/{repo_group_name}/_settings/integrations/{integration}/new'),
repo_group_route=True,
valid_integration=True)
config.add_view(RepoGroupIntegrationsView,
attr='settings_get',
renderer='rhodecode:templates/admin/integrations/form.mako',
request_method='GET',
route_name='repo_group_integrations_create')
config.add_view(RepoGroupIntegrationsView,
attr='settings_post',
renderer='rhodecode:templates/admin/integrations/form.mako',
request_method='POST',
route_name='repo_group_integrations_create')
config.add_route(
"repo_group_integrations_create",
add_route_requirements("/{repo_group_name}/_settings/integrations/{integration}/new"),
repo_group_route=True,
valid_integration=True,
)
config.add_view(
RepoGroupIntegrationsView,
attr="settings_get",
renderer="rhodecode:templates/admin/integrations/form.mako",
request_method="GET",
route_name="repo_group_integrations_create",
)
config.add_view(
RepoGroupIntegrationsView,
attr="settings_post",
renderer="rhodecode:templates/admin/integrations/form.mako",
request_method="POST",
route_name="repo_group_integrations_create",
)
config.add_route('repo_group_integrations_edit',
add_route_requirements('/{repo_group_name}/_settings/integrations/{integration}/{integration_id}'),
repo_group_route=True,
valid_integration=True)
config.add_route(
"repo_group_integrations_edit",
add_route_requirements("/{repo_group_name}/_settings/integrations/{integration}/{integration_id}"),
repo_group_route=True,
valid_integration=True,
)
config.add_view(RepoGroupIntegrationsView,
attr='settings_get',
renderer='rhodecode:templates/admin/integrations/form.mako',
request_method='GET',
route_name='repo_group_integrations_edit')
config.add_view(RepoGroupIntegrationsView,
attr='settings_post',
renderer='rhodecode:templates/admin/integrations/form.mako',
request_method='POST',
route_name='repo_group_integrations_edit')
config.add_view(
RepoGroupIntegrationsView,
attr="settings_get",
renderer="rhodecode:templates/admin/integrations/form.mako",
request_method="GET",
route_name="repo_group_integrations_edit",
)
config.add_view(
RepoGroupIntegrationsView,
attr="settings_post",
renderer="rhodecode:templates/admin/integrations/form.mako",
request_method="POST",
route_name="repo_group_integrations_edit",
)
# repo integrations
config.add_route('repo_integrations_home',
add_route_requirements('/{repo_name}/settings/integrations'),
repo_route=True)
config.add_view(RepoIntegrationsView,
attr='integration_list',
request_method='GET',
renderer='rhodecode:templates/admin/integrations/list.mako',
route_name='repo_integrations_home')
config.add_route(
"repo_integrations_home", add_route_requirements("/{repo_name}/settings/integrations"), repo_route=True
)
config.add_view(
RepoIntegrationsView,
attr="integration_list",
request_method="GET",
renderer="rhodecode:templates/admin/integrations/list.mako",
route_name="repo_integrations_home",
)
config.add_route('repo_integrations_new',
add_route_requirements('/{repo_name}/settings/integrations/new'),
repo_route=True)
config.add_view(RepoIntegrationsView,
attr='new_integration',
renderer='rhodecode:templates/admin/integrations/new.mako',
request_method='GET',
route_name='repo_integrations_new')
config.add_route(
"repo_integrations_new", add_route_requirements("/{repo_name}/settings/integrations/new"), repo_route=True
)
config.add_view(
RepoIntegrationsView,
attr="new_integration",
renderer="rhodecode:templates/admin/integrations/new.mako",
request_method="GET",
route_name="repo_integrations_new",
)
config.add_route('repo_integrations_list',
add_route_requirements('/{repo_name}/settings/integrations/{integration}'),
repo_route=True,
valid_integration=True)
config.add_view(RepoIntegrationsView,
attr='integration_list',
request_method='GET',
renderer='rhodecode:templates/admin/integrations/list.mako',
route_name='repo_integrations_list')
config.add_route(
"repo_integrations_list",
add_route_requirements("/{repo_name}/settings/integrations/{integration}"),
repo_route=True,
valid_integration=True,
)
config.add_view(
RepoIntegrationsView,
attr="integration_list",
request_method="GET",
renderer="rhodecode:templates/admin/integrations/list.mako",
route_name="repo_integrations_list",
)
config.add_route('repo_integrations_create',
add_route_requirements('/{repo_name}/settings/integrations/{integration}/new'),
repo_route=True,
valid_integration=True)
config.add_view(RepoIntegrationsView,
attr='settings_get',
renderer='rhodecode:templates/admin/integrations/form.mako',
request_method='GET',
route_name='repo_integrations_create')
config.add_view(RepoIntegrationsView,
attr='settings_post',
renderer='rhodecode:templates/admin/integrations/form.mako',
request_method='POST',
route_name='repo_integrations_create')
config.add_route(
"repo_integrations_create",
add_route_requirements("/{repo_name}/settings/integrations/{integration}/new"),
repo_route=True,
valid_integration=True,
)
config.add_view(
RepoIntegrationsView,
attr="settings_get",
renderer="rhodecode:templates/admin/integrations/form.mako",
request_method="GET",
route_name="repo_integrations_create",
)
config.add_view(
RepoIntegrationsView,
attr="settings_post",
renderer="rhodecode:templates/admin/integrations/form.mako",
request_method="POST",
route_name="repo_integrations_create",
)
config.add_route('repo_integrations_edit',
add_route_requirements('/{repo_name}/settings/integrations/{integration}/{integration_id}'),
repo_route=True,
valid_integration=True)
config.add_view(RepoIntegrationsView,
attr='settings_get',
renderer='rhodecode:templates/admin/integrations/form.mako',
request_method='GET',
route_name='repo_integrations_edit')
config.add_view(RepoIntegrationsView,
attr='settings_post',
renderer='rhodecode:templates/admin/integrations/form.mako',
request_method='POST',
route_name='repo_integrations_edit')
config.add_route(
"repo_integrations_edit",
add_route_requirements("/{repo_name}/settings/integrations/{integration}/{integration_id}"),
repo_route=True,
valid_integration=True,
)
config.add_view(
RepoIntegrationsView,
attr="settings_get",
renderer="rhodecode:templates/admin/integrations/form.mako",
request_method="GET",
route_name="repo_integrations_edit",
)
config.add_view(
RepoIntegrationsView,
attr="settings_post",
renderer="rhodecode:templates/admin/integrations/form.mako",
request_method="POST",
route_name="repo_integrations_edit",
)

View file

@ -25,16 +25,16 @@ class IntegrationOptionsSchemaBase(colander.MappingSchema):
enabled = colander.SchemaNode(
colander.Bool(),
default=True,
description=_('Enable or disable this integration.'),
description=_("Enable or disable this integration."),
missing=False,
title=_('Enabled'),
title=_("Enabled"),
)
name = colander.SchemaNode(
colander.String(),
description=_('Short name for this integration.'),
description=_("Short name for this integration."),
missing=colander.required,
title=_('Integration name'),
title=_("Integration name"),
)
@ -47,10 +47,11 @@ class RepoGroupIntegrationOptionsSchema(IntegrationOptionsSchemaBase):
colander.Bool(),
default=True,
description=_(
'Limit integrations to to work only on the direct children '
'repositories of this repository group (no subgroups)'),
"Limit integrations to to work only on the direct children "
"repositories of this repository group (no subgroups)"
),
missing=False,
title=_('Limit to childen repos only'),
title=_("Limit to childen repos only"),
)
@ -58,10 +59,9 @@ class GlobalIntegrationOptionsSchema(IntegrationOptionsSchemaBase):
child_repos_only = colander.SchemaNode(
colander.Bool(),
default=False,
description=_(
'Limit integrations to to work only on root level repositories'),
description=_("Limit integrations to to work only on root level repositories"),
missing=False,
title=_('Root repositories only'),
title=_("Root repositories only"),
)

View file

@ -25,8 +25,7 @@ from rhodecode.integrations import integration_type_registry
from rhodecode.tests.routes import route_path
def _post_integration_test_helper(app, url, csrf_token, repo, repo_group,
admin_view):
def _post_integration_test_helper(app, url, csrf_token, repo, repo_group, admin_view):
"""
Posts form data to create integration at the url given then deletes it and
checks if the redirect url is correct.
@ -34,193 +33,170 @@ def _post_integration_test_helper(app, url, csrf_token, repo, repo_group,
repo_name = repo.repo_name
repo_group_name = repo_group.group_name
app.post(url, params={}, status=403) # missing csrf check
response = app.post(url, params={'csrf_token': csrf_token})
response = app.post(url, params={"csrf_token": csrf_token})
assert response.status_code == 200
response.mustcontain('Errors exist')
response.mustcontain("Errors exist")
scopes_destinations = [
('global',
ADMIN_PREFIX + '/integrations'),
('root-repos',
ADMIN_PREFIX + '/integrations'),
('repo:%s' % repo_name,
'/%s/settings/integrations' % repo_name),
('repogroup:%s' % repo_group_name,
'/%s/_settings/integrations' % repo_group_name),
('repogroup-recursive:%s' % repo_group_name,
'/%s/_settings/integrations' % repo_group_name),
("global", ADMIN_PREFIX + "/integrations"),
("root-repos", ADMIN_PREFIX + "/integrations"),
("repo:%s" % repo_name, "/%s/settings/integrations" % repo_name),
("repogroup:%s" % repo_group_name, "/%s/_settings/integrations" % repo_group_name),
("repogroup-recursive:%s" % repo_group_name, "/%s/_settings/integrations" % repo_group_name),
]
for scope, destination in scopes_destinations:
if admin_view:
destination = ADMIN_PREFIX + '/integrations'
destination = ADMIN_PREFIX + "/integrations"
form_data = [
('csrf_token', csrf_token),
('__start__', 'options:mapping'),
('name', 'test integration'),
('scope', scope),
('enabled', 'true'),
('__end__', 'options:mapping'),
('__start__', 'settings:mapping'),
('test_int_field', '34'),
('test_string_field', ''), # empty value on purpose as it's required
('__end__', 'settings:mapping'),
("csrf_token", csrf_token),
("__start__", "options:mapping"),
("name", "test integration"),
("scope", scope),
("enabled", "true"),
("__end__", "options:mapping"),
("__start__", "settings:mapping"),
("test_int_field", "34"),
("test_string_field", ""), # empty value on purpose as it's required
("__end__", "settings:mapping"),
]
errors_response = app.post(url, form_data)
assert 'Errors exist' in errors_response.text
assert "Errors exist" in errors_response.text
form_data[-2] = ('test_string_field', 'data!')
form_data[-2] = ("test_string_field", "data!")
assert Session().query(Integration).count() == 0
created_response = app.post(url, form_data)
assert Session().query(Integration).count() == 1
delete_response = app.post(
created_response.location,
params={'csrf_token': csrf_token, 'delete': 'delete'})
delete_response = app.post(created_response.location, params={"csrf_token": csrf_token, "delete": "delete"})
assert Session().query(Integration).count() == 0
assert delete_response.location.endswith(destination)
@pytest.mark.usefixtures('app', 'autologin_user')
@pytest.mark.usefixtures("app", "autologin_user")
class TestIntegrationsView(object):
pass
class TestGlobalIntegrationsView(TestIntegrationsView):
def test_index_no_integrations(self):
url = ADMIN_PREFIX + '/integrations'
url = ADMIN_PREFIX + "/integrations"
response = self.app.get(url)
assert response.status_code == 200
response.mustcontain('exist yet')
response.mustcontain("exist yet")
def test_index_with_integrations(self, global_integration_stub):
url = ADMIN_PREFIX + '/integrations'
url = ADMIN_PREFIX + "/integrations"
response = self.app.get(url)
assert response.status_code == 200
response.mustcontain(no=['exist yet'])
response.mustcontain(no=["exist yet"])
response.mustcontain(global_integration_stub.name)
@pytest.mark.parametrize(
'IntegrationType', integration_type_registry.values())
@pytest.mark.parametrize("IntegrationType", integration_type_registry.values())
def test_new_integration_page(self, IntegrationType):
url = ADMIN_PREFIX + '/integrations/new'
url = ADMIN_PREFIX + "/integrations/new"
response = self.app.get(url, status=200)
if not IntegrationType.is_dummy:
url = (ADMIN_PREFIX + '/integrations/{integration}/new').format(
integration=IntegrationType.key)
url = (ADMIN_PREFIX + "/integrations/{integration}/new").format(integration=IntegrationType.key)
response.mustcontain(url)
@pytest.mark.parametrize(
'IntegrationType', integration_type_registry.values())
@pytest.mark.parametrize("IntegrationType", integration_type_registry.values())
def test_get_create_integration_page(self, IntegrationType):
url = ADMIN_PREFIX + '/integrations/{integration_key}/new'.format(
integration_key=IntegrationType.key)
url = ADMIN_PREFIX + "/integrations/{integration_key}/new".format(integration_key=IntegrationType.key)
if IntegrationType.is_dummy:
self.app.get(url, status=404)
else:
response = self.app.get(url, status=200)
response.mustcontain(IntegrationType.display_name)
def test_post_integration_page(self, StubIntegrationType, csrf_token,
test_repo_group, backend_random):
url = ADMIN_PREFIX + '/integrations/{integration_key}/new'.format(
integration_key=StubIntegrationType.key)
def test_post_integration_page(self, StubIntegrationType, csrf_token, test_repo_group, backend_random):
url = ADMIN_PREFIX + "/integrations/{integration_key}/new".format(integration_key=StubIntegrationType.key)
_post_integration_test_helper(
self.app, url, csrf_token, admin_view=True,
repo=backend_random.repo, repo_group=test_repo_group)
self.app, url, csrf_token, admin_view=True, repo=backend_random.repo, repo_group=test_repo_group
)
class TestRepoIntegrationsView(TestIntegrationsView):
def test_index_no_integrations(self, backend_random):
url = '/{repo_name}/settings/integrations'.format(
repo_name=backend_random.repo.repo_name)
url = "/{repo_name}/settings/integrations".format(repo_name=backend_random.repo.repo_name)
response = self.app.get(url)
assert response.status_code == 200
response.mustcontain('exist yet')
response.mustcontain("exist yet")
def test_index_with_integrations(self, repo_integration_stub):
url = '/{repo_name}/settings/integrations'.format(
repo_name=repo_integration_stub.repo.repo_name)
url = "/{repo_name}/settings/integrations".format(repo_name=repo_integration_stub.repo.repo_name)
stub_name = repo_integration_stub.name
response = self.app.get(url)
assert response.status_code == 200
response.mustcontain(stub_name)
response.mustcontain(no=['exist yet'])
response.mustcontain(no=["exist yet"])
@pytest.mark.parametrize(
'IntegrationType', integration_type_registry.values())
@pytest.mark.parametrize("IntegrationType", integration_type_registry.values())
def test_new_integration_page(self, backend_random, IntegrationType):
repo_name = backend_random.repo.repo_name
url = '/{repo_name}/settings/integrations/new'.format(
repo_name=repo_name)
url = "/{repo_name}/settings/integrations/new".format(repo_name=repo_name)
response = self.app.get(url, status=200)
url = '/{repo_name}/settings/integrations/{integration}/new'.format(
repo_name=repo_name,
integration=IntegrationType.key)
url = "/{repo_name}/settings/integrations/{integration}/new".format(
repo_name=repo_name, integration=IntegrationType.key
)
if not IntegrationType.is_dummy:
response.mustcontain(url)
@pytest.mark.parametrize(
'IntegrationType', integration_type_registry.values())
@pytest.mark.parametrize("IntegrationType", integration_type_registry.values())
def test_get_create_integration_page(self, backend_random, IntegrationType):
repo_name = backend_random.repo.repo_name
url = '/{repo_name}/settings/integrations/{integration_key}/new'.format(
repo_name=repo_name, integration_key=IntegrationType.key)
url = "/{repo_name}/settings/integrations/{integration_key}/new".format(
repo_name=repo_name, integration_key=IntegrationType.key
)
if IntegrationType.is_dummy:
self.app.get(url, status=404)
else:
response = self.app.get(url, status=200)
response.mustcontain(IntegrationType.display_name)
def test_post_integration_page(self, backend_random, test_repo_group,
StubIntegrationType, csrf_token):
def test_post_integration_page(self, backend_random, test_repo_group, StubIntegrationType, csrf_token):
repo_name = backend_random.repo.repo_name
url = '/{repo_name}/settings/integrations/{integration_key}/new'.format(
repo_name=repo_name, integration_key=StubIntegrationType.key)
url = "/{repo_name}/settings/integrations/{integration_key}/new".format(
repo_name=repo_name, integration_key=StubIntegrationType.key
)
_post_integration_test_helper(
self.app, url, csrf_token, admin_view=False,
repo=backend_random.repo, repo_group=test_repo_group)
self.app, url, csrf_token, admin_view=False, repo=backend_random.repo, repo_group=test_repo_group
)
class TestRepoGroupIntegrationsView(TestIntegrationsView):
def test_index_no_integrations(self, test_repo_group):
url = '/{repo_group_name}/_settings/integrations'.format(
repo_group_name=test_repo_group.group_name)
url = "/{repo_group_name}/_settings/integrations".format(repo_group_name=test_repo_group.group_name)
response = self.app.get(url)
assert response.status_code == 200
response.mustcontain('exist yet')
response.mustcontain("exist yet")
def test_index_with_integrations(
self, test_repo_group, repogroup_integration_stub):
url = '/{repo_group_name}/_settings/integrations'.format(
repo_group_name=test_repo_group.group_name)
def test_index_with_integrations(self, test_repo_group, repogroup_integration_stub):
url = "/{repo_group_name}/_settings/integrations".format(repo_group_name=test_repo_group.group_name)
stub_name = repogroup_integration_stub.name
response = self.app.get(url)
assert response.status_code == 200
response.mustcontain(no=['exist yet'])
response.mustcontain(no=["exist yet"])
response.mustcontain(stub_name)
def test_new_integration_page(self, test_repo_group):
repo_group_name = test_repo_group.group_name
url = '/{repo_group_name}/_settings/integrations/new'.format(
repo_group_name=test_repo_group.group_name)
url = "/{repo_group_name}/_settings/integrations/new".format(repo_group_name=test_repo_group.group_name)
response = self.app.get(url)
@ -228,21 +204,17 @@ class TestRepoGroupIntegrationsView(TestIntegrationsView):
for integration_key, integration_obj in integration_type_registry.items():
if not integration_obj.is_dummy:
nurl = (
'/{repo_group_name}/_settings/integrations/{integration}/new').format(
repo_group_name=repo_group_name,
integration=integration_key)
nurl = ("/{repo_group_name}/_settings/integrations/{integration}/new").format(
repo_group_name=repo_group_name, integration=integration_key
)
response.mustcontain(nurl)
@pytest.mark.parametrize(
'IntegrationType', integration_type_registry.values())
def test_get_create_integration_page(
self, test_repo_group, IntegrationType):
@pytest.mark.parametrize("IntegrationType", integration_type_registry.values())
def test_get_create_integration_page(self, test_repo_group, IntegrationType):
repo_group_name = test_repo_group.group_name
url = ('/{repo_group_name}/_settings/integrations/{integration_key}/new'
).format(repo_group_name=repo_group_name,
integration_key=IntegrationType.key)
url = ("/{repo_group_name}/_settings/integrations/{integration_key}/new").format(
repo_group_name=repo_group_name, integration_key=IntegrationType.key
)
if not IntegrationType.is_dummy:
response = self.app.get(url, status=200)
@ -250,14 +222,12 @@ class TestRepoGroupIntegrationsView(TestIntegrationsView):
else:
self.app.get(url, status=404)
def test_post_integration_page(self, test_repo_group, backend_random,
StubIntegrationType, csrf_token):
def test_post_integration_page(self, test_repo_group, backend_random, StubIntegrationType, csrf_token):
repo_group_name = test_repo_group.group_name
url = ('/{repo_group_name}/_settings/integrations/{integration_key}/new'
).format(repo_group_name=repo_group_name,
integration_key=StubIntegrationType.key)
url = ("/{repo_group_name}/_settings/integrations/{integration_key}/new").format(
repo_group_name=repo_group_name, integration_key=StubIntegrationType.key
)
_post_integration_test_helper(
self.app, url, csrf_token, admin_view=False,
repo=backend_random.repo, repo_group=test_repo_group)
self.app, url, csrf_token, admin_view=False, repo=backend_random.repo, repo_group=test_repo_group
)

View file

@ -38,7 +38,6 @@ log = logging.getLogger(__name__)
class UrlTmpl(string.Template):
def safe_substitute(self, **kws):
# url encode the kw for usage in url
kws = {k: urllib.parse.quote(safe_str(v)) for k, v in kws.items()}
@ -46,13 +45,14 @@ class UrlTmpl(string.Template):
class IntegrationTypeBase(object):
""" Base class for IntegrationType plugins """
"""Base class for IntegrationType plugins"""
is_dummy = False
description = ''
description = ""
@classmethod
def icon(cls):
return '''
return """
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
@ -112,7 +112,7 @@ class IntegrationTypeBase(object):
style="fill:currentColor" />
</g>
</svg>
'''
"""
def __init__(self, settings):
"""
@ -132,16 +132,15 @@ class IntegrationTypeBase(object):
:param event:
:return: bool
"""
allowed_events = self.settings.get('events') or []
allowed_events = self.settings.get("events") or []
if event.name not in allowed_events:
log.debug('event ignored: %r event %s not in allowed set of events %s',
event, event.name, allowed_events)
log.debug("event ignored: %r event %s not in allowed set of events %s", event, event.name, allowed_events)
return False
return True
class EEIntegration(IntegrationTypeBase):
description = 'Integration available in RhodeCode EE edition.'
description = "Integration available in RhodeCode EE edition."
is_dummy = True
def __init__(self, name, key, settings=None):
@ -154,55 +153,64 @@ class EEIntegration(IntegrationTypeBase):
# updating this required to update the `common_vars` as well.
WEBHOOK_URL_VARS = [
# GENERAL
('General', [
('event_name', 'Unique name of the event type, e.g pullrequest-update'),
('repo_name', 'Full name of the repository'),
('repo_type', 'VCS type of repository'),
('repo_id', 'Unique id of repository'),
('repo_url', 'Repository url'),
]
(
"General",
[
("event_name", "Unique name of the event type, e.g pullrequest-update"),
("repo_name", "Full name of the repository"),
("repo_type", "VCS type of repository"),
("repo_id", "Unique id of repository"),
("repo_url", "Repository url"),
],
),
# extra repo fields
('Repository', [
('extra:<extra_key_name>', 'Extra repo variables, read from its settings.'),
]
(
"Repository",
[
("extra:<extra_key_name>", "Extra repo variables, read from its settings."),
],
),
# special attrs below that we handle, using multi-call
('Commit push - Multicalls', [
('branch', 'Name of each branch submitted, if any.'),
('branch_head', 'Head ID of pushed branch (full sha of last commit), if any.'),
('commit_id', 'ID (full sha) of each commit submitted, if any.'),
]
(
"Commit push - Multicalls",
[
("branch", "Name of each branch submitted, if any."),
("branch_head", "Head ID of pushed branch (full sha of last commit), if any."),
("commit_id", "ID (full sha) of each commit submitted, if any."),
],
),
# pr events vars
('Pull request', [
('pull_request_id', 'Unique ID of the pull request.'),
('pull_request_title', 'Title of the pull request.'),
('pull_request_url', 'Pull request url.'),
('pull_request_shadow_url', 'Pull request shadow repo clone url.'),
('pull_request_commits_uid', 'Calculated UID of all commits inside the PR. '
'Changes after PR update'),
]
(
"Pull request",
[
("pull_request_id", "Unique ID of the pull request."),
("pull_request_title", "Title of the pull request."),
("pull_request_url", "Pull request url."),
("pull_request_shadow_url", "Pull request shadow repo clone url."),
("pull_request_commits_uid", "Calculated UID of all commits inside the PR. Changes after PR update"),
],
),
# commit comment event vars
('Commit comment', [
('commit_comment_id', 'Unique ID of the comment made on a commit.'),
('commit_comment_text', 'Text of commit comment.'),
('commit_comment_type', 'Type of comment, e.g note/todo.'),
('commit_comment_f_path', 'Optionally path of file for inline comments.'),
('commit_comment_line_no', 'Line number of the file: eg o10, or n200'),
('commit_comment_commit_id', 'Commit id that comment was left at.'),
('commit_comment_commit_branch', 'Commit branch that comment was left at'),
('commit_comment_commit_message', 'Commit message that comment was left at'),
]
(
"Commit comment",
[
("commit_comment_id", "Unique ID of the comment made on a commit."),
("commit_comment_text", "Text of commit comment."),
("commit_comment_type", "Type of comment, e.g note/todo."),
("commit_comment_f_path", "Optionally path of file for inline comments."),
("commit_comment_line_no", "Line number of the file: eg o10, or n200"),
("commit_comment_commit_id", "Commit id that comment was left at."),
("commit_comment_commit_branch", "Commit branch that comment was left at"),
("commit_comment_commit_message", "Commit message that comment was left at"),
],
),
# user who triggers the call
('Caller', [
('username', 'User who triggered the call.'),
('user_id', 'User id who triggered the call.'),
]
(
"Caller",
[
("username", "User who triggered the call."),
("user_id", "User id who triggered the call."),
],
),
]
@ -211,55 +219,52 @@ CI_URL_VARS = WEBHOOK_URL_VARS
class CommitParsingDataHandler(object):
def aggregate_branch_data(self, branches, commits):
branch_data = collections.OrderedDict()
for obj in branches:
branch_data[obj['name']] = obj
branch_data[obj["name"]] = obj
branches_commits = collections.OrderedDict()
for commit in commits:
if commit.get('git_ref_change'):
if commit.get("git_ref_change"):
# special case for GIT that allows creating tags,
# deleting branches without associated commit
continue
commit_branch = commit['branch']
commit_branch = commit["branch"]
if commit_branch not in branches_commits:
_branch = branch_data[commit_branch] \
if commit_branch else commit_branch
branch_commits = {'branch': _branch,
'branch_head': '',
'commits': []}
_branch = branch_data[commit_branch] if commit_branch else commit_branch
branch_commits = {"branch": _branch, "branch_head": "", "commits": []}
branches_commits[commit_branch] = branch_commits
branch_commits = branches_commits[commit_branch]
branch_commits['commits'].append(commit)
branch_commits['branch_head'] = commit['raw_id']
branch_commits["commits"].append(commit)
branch_commits["branch_head"] = commit["raw_id"]
return branches_commits
def get_auth(settings):
from requests.auth import HTTPBasicAuth
username = settings.get('username')
password = settings.get('password')
username = settings.get("username")
password = settings.get("password")
if username and password:
return HTTPBasicAuth(username, password)
return None
def get_web_token(settings):
return settings['secret_token']
return settings["secret_token"]
def get_url_vars(url_vars):
items = []
for section, section_items in url_vars:
items.append(f'\n*{section}*')
items.append(f"\n*{section}*")
for key, explanation in section_items:
items.append(' {} - {}'.format('${' + key + '}', explanation))
return '\n'.join(items)
items.append(" {} - {}".format("${" + key + "}", explanation))
return "\n".join(items)
def render_with_traceback(template, *args, **kwargs):
@ -274,9 +279,7 @@ STATUS_400 = (400, 401, 403)
STATUS_500 = (500, 502, 504)
def requests_retry_call(
retries=3, backoff_factor=0.3, status_forcelist=STATUS_400+STATUS_500,
session=None):
def requests_retry_call(retries=3, backoff_factor=0.3, status_forcelist=STATUS_400 + STATUS_500, session=None):
"""
session = requests_retry_session()
response = session.get('http://example.com')
@ -295,6 +298,6 @@ def requests_retry_call(
status_forcelist=status_forcelist,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session

View file

@ -28,13 +28,12 @@ from rhodecode.model.validation_schema.widgets import CheckboxChoiceWidgetDesc
from rhodecode.translation import _
from rhodecode.lib.celerylib import run_task
from rhodecode.lib.celerylib import tasks
from rhodecode.integrations.types.base import (
IntegrationTypeBase, render_with_traceback)
from rhodecode.integrations.types.base import IntegrationTypeBase, render_with_traceback
log = logging.getLogger(__name__)
REPO_PUSH_TEMPLATE_PLAINTEXT = Template('''
REPO_PUSH_TEMPLATE_PLAINTEXT = Template("""
Commits:
% for commit in data['push']['commits']:
@ -43,9 +42,9 @@ ${commit['message']}
----
% endfor
''')
""")
REPO_PUSH_TEMPLATE_HTML = Template('''
REPO_PUSH_TEMPLATE_HTML = Template("""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
@ -146,40 +145,38 @@ REPO_PUSH_TEMPLATE_HTML = Template('''
</a></p>
</body>
</html>
''')
""")
class EmailSettingsSchema(colander.Schema):
@colander.instantiate(validator=colander.Length(min=1))
class recipients(colander.SequenceSchema):
title = _('Recipients')
description = _('Email addresses to send push events to')
title = _("Recipients")
description = _("Email addresses to send push events to")
widget = deform.widget.SequenceWidget(min_len=1)
recipient = colander.SchemaNode(
colander.String(),
title=_('Email address'),
description=_('Email address'),
default='',
title=_("Email address"),
description=_("Email address"),
default="",
validator=colander.Email(),
widget=deform.widget.TextInputWidget(
placeholder='user@domain.com',
placeholder="user@domain.com",
),
)
class EmailIntegrationType(IntegrationTypeBase):
key = 'email'
display_name = _('Email')
description = _('Send repo push summaries to a list of recipients via email')
key = "email"
display_name = _("Email")
description = _("Send repo push summaries to a list of recipients via email")
valid_events = [
events.RepoPushEvent
]
valid_events = [events.RepoPushEvent]
@classmethod
def icon(cls):
return '''
return """
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
@ -239,27 +236,27 @@ class EmailIntegrationType(IntegrationTypeBase):
style="fill:currentColor" />
</g>
</svg>
'''
"""
def settings_schema(self):
schema = EmailSettingsSchema()
schema.add(colander.SchemaNode(
colander.Set(),
widget=CheckboxChoiceWidgetDesc(
values=sorted(
[(e.name, e.display_name, e.description) for e in self.valid_events]
schema.add(
colander.SchemaNode(
colander.Set(),
widget=CheckboxChoiceWidgetDesc(
values=sorted([(e.name, e.display_name, e.description) for e in self.valid_events]),
),
),
description="List of events activated for this integration",
name='events'
))
description="List of events activated for this integration",
name="events",
)
)
return schema
def send_event(self, event):
log.debug('handling event %s with integration %s', event.name, self)
log.debug("handling event %s with integration %s", event.name, self)
if event.__class__ not in self.valid_events:
log.debug('event %r not present in valid event list (%s)', event, self.valid_events)
log.debug("event %r not present in valid event list (%s)", event, self.valid_events)
return
if not self.event_enabled(event):
@ -279,49 +276,43 @@ class EmailEventHandler(object):
if isinstance(event, events.RepoPushEvent):
self.repo_push_handler(event, event_data)
else:
log.debug('ignoring event: %r', event)
log.debug("ignoring event: %r", event)
def repo_push_handler(self, event, data):
commit_num = len(data['push']['commits'])
server_url = data['server_url']
commit_num = len(data["push"]["commits"])
server_url = data["server_url"]
if commit_num == 1:
if data['push']['branches']:
_subject = '[{repo_name}] {author} pushed {commit_num} commit on branches: {branches}'
if data["push"]["branches"]:
_subject = "[{repo_name}] {author} pushed {commit_num} commit on branches: {branches}"
else:
_subject = '[{repo_name}] {author} pushed {commit_num} commit'
_subject = "[{repo_name}] {author} pushed {commit_num} commit"
subject = _subject.format(
author=data['actor']['username'],
repo_name=data['repo']['repo_name'],
author=data["actor"]["username"],
repo_name=data["repo"]["repo_name"],
commit_num=commit_num,
branches=', '.join(
branch['name'] for branch in data['push']['branches'])
branches=", ".join(branch["name"] for branch in data["push"]["branches"]),
)
else:
if data['push']['branches']:
_subject = '[{repo_name}] {author} pushed {commit_num} commits on branches: {branches}'
if data["push"]["branches"]:
_subject = "[{repo_name}] {author} pushed {commit_num} commits on branches: {branches}"
else:
_subject = '[{repo_name}] {author} pushed {commit_num} commits'
_subject = "[{repo_name}] {author} pushed {commit_num} commits"
subject = _subject.format(
author=data['actor']['username'],
repo_name=data['repo']['repo_name'],
author=data["actor"]["username"],
repo_name=data["repo"]["repo_name"],
commit_num=commit_num,
branches=', '.join(
branch['name'] for branch in data['push']['branches']))
branches=", ".join(branch["name"] for branch in data["push"]["branches"]),
)
email_body_plaintext = render_with_traceback(
REPO_PUSH_TEMPLATE_PLAINTEXT,
data=data,
subject=subject,
instance_url=server_url)
REPO_PUSH_TEMPLATE_PLAINTEXT, data=data, subject=subject, instance_url=server_url
)
email_body_html = render_with_traceback(
REPO_PUSH_TEMPLATE_HTML,
data=data,
subject=subject,
instance_url=server_url)
REPO_PUSH_TEMPLATE_HTML, data=data, subject=subject, instance_url=server_url
)
recipients = self.integration_settings['recipients']
recipients = self.integration_settings["recipients"]
for email_address in recipients:
run_task(tasks.send_email, email_address, subject,
email_body_plaintext, email_body_html)
run_task(tasks.send_email, email_address, subject, email_body_plaintext, email_body_html)

View file

@ -37,10 +37,10 @@ class SlackData:
def html_to_slack_links(message):
return re.compile(r'<a .*?href=["\'](.+?)".*?>(.+?)</a>').sub(r'<\1|\2>', message)
return re.compile(r'<a .*?href=["\'](.+?)".*?>(.+?)</a>').sub(r"<\1|\2>", message)
REPO_PUSH_TEMPLATE = Template('''
REPO_PUSH_TEMPLATE = Template("""
<%
def branch_text(branch):
if branch:
@ -56,11 +56,11 @@ ${len(branch_commits['commits'])} ${'commit' if len(branch_commits['commits']) =
`<${commit['url']}|${commit['short_id']}>` - ${commit['message_html']|html_to_slack_links}
% endfor
% endfor
''')
""")
class SlackDataHandler(CommitParsingDataHandler):
name = 'slack'
name = "slack"
def __init__(self):
pass
@ -70,19 +70,15 @@ class SlackDataHandler(CommitParsingDataHandler):
raise TypeError(f"event {event} is not subtype of events.RhodecodeEvent")
actor = data["actor"]["username"]
default_title = f'*{actor}* caused a *{event.name}* event'
default_text = f'*{actor}* caused a *{event.name}* event'
default_title = f"*{actor}* caused a *{event.name}* event"
default_text = f"*{actor}* caused a *{event.name}* event"
default_slack_data = SlackData(title=default_title, text=default_text)
if isinstance(event, events.PullRequestCommentEvent):
return self.format_pull_request_comment_event(
event, data, default_slack_data
)
return self.format_pull_request_comment_event(event, data, default_slack_data)
elif isinstance(event, events.PullRequestCommentEditEvent):
return self.format_pull_request_comment_event(
event, data, default_slack_data
)
return self.format_pull_request_comment_event(event, data, default_slack_data)
elif isinstance(event, events.PullRequestReviewEvent):
return self.format_pull_request_review_event(event, data, default_slack_data)
elif isinstance(event, events.PullRequestEvent):
@ -92,61 +88,53 @@ class SlackDataHandler(CommitParsingDataHandler):
elif isinstance(event, events.RepoCreateEvent):
return self.format_repo_create_event(event, data, default_slack_data)
else:
raise ValueError(
f'event type `{event.__class__}` has no handler defined')
raise ValueError(f"event type `{event.__class__}` has no handler defined")
def format_pull_request_comment_event(self, event, data, slack_data):
comment_text = data['comment']['text']
comment_text = data["comment"]["text"]
if len(comment_text) > 200:
comment_text = '<{comment_url}|{comment_text}...>'.format(
comment_text = "<{comment_url}|{comment_text}...>".format(
comment_text=comment_text[:200],
comment_url=data['comment']['url'],
comment_url=data["comment"]["url"],
)
fields = None
overrides = None
status_text = None
if data['comment']['status']:
status_color = {
'approved': '#0ac878',
'rejected': '#e85e4d'}.get(data['comment']['status'])
if data["comment"]["status"]:
status_color = {"approved": "#0ac878", "rejected": "#e85e4d"}.get(data["comment"]["status"])
if status_color:
overrides = {"color": status_color}
status_text = data['comment']['status']
status_text = data["comment"]["status"]
if data['comment']['file']:
if data["comment"]["file"]:
fields = [
{
"title": "file",
"value": data['comment']['file']
},
{
"title": "line",
"value": data['comment']['line']
}
{"title": "file", "value": data["comment"]["file"]},
{"title": "line", "value": data["comment"]["line"]},
]
template = Template(textwrap.dedent(r'''
template = Template(
textwrap.dedent(r"""
*${data['actor']['username']}* left ${data['comment']['type']} on pull request <${data['pullrequest']['url']}|#${data['pullrequest']['pull_request_id']}>:
'''))
title = render_with_traceback(
template, data=data, comment=event.comment)
""")
)
title = render_with_traceback(template, data=data, comment=event.comment)
template = Template(textwrap.dedent(r'''
template = Template(
textwrap.dedent(r"""
*pull request title*: ${pr_title}
% if status_text:
*submitted status*: `${status_text}`
% endif
>>> ${comment_text}
'''))
""")
)
text = render_with_traceback(
template,
comment_text=comment_text,
pr_title=data['pullrequest']['title'],
status_text=status_text)
template, comment_text=comment_text, pr_title=data["pullrequest"]["title"], status_text=status_text
)
slack_data.title = title
slack_data.text = text
@ -156,17 +144,19 @@ class SlackDataHandler(CommitParsingDataHandler):
return slack_data
def format_pull_request_review_event(self, event, data, slack_data) -> SlackData:
template = Template(textwrap.dedent(r'''
template = Template(
textwrap.dedent(r"""
*${data['actor']['username']}* changed status of pull request <${data['pullrequest']['url']}|#${data['pullrequest']['pull_request_id']} to `${data['pullrequest']['status']}`>:
'''))
""")
)
title = render_with_traceback(template, data=data)
template = Template(textwrap.dedent(r'''
template = Template(
textwrap.dedent(r"""
*pull request title*: ${pr_title}
'''))
text = render_with_traceback(
template,
pr_title=data['pullrequest']['title'])
""")
)
text = render_with_traceback(template, pr_title=data["pullrequest"]["title"])
slack_data.title = title
slack_data.text = text
@ -175,27 +165,28 @@ class SlackDataHandler(CommitParsingDataHandler):
def format_pull_request_event(self, event, data, slack_data) -> SlackData:
action = {
events.PullRequestCloseEvent: 'closed',
events.PullRequestMergeEvent: 'merged',
events.PullRequestUpdateEvent: 'updated',
events.PullRequestCreateEvent: 'created',
events.PullRequestCloseEvent: "closed",
events.PullRequestMergeEvent: "merged",
events.PullRequestUpdateEvent: "updated",
events.PullRequestCreateEvent: "created",
}.get(event.__class__, str(event.__class__))
template = Template(textwrap.dedent(r'''
template = Template(
textwrap.dedent(r"""
*${data['actor']['username']}* `${action}` pull request <${data['pullrequest']['url']}|#${data['pullrequest']['pull_request_id']}>:
'''))
""")
)
title = render_with_traceback(template, data=data, action=action)
template = Template(textwrap.dedent(r'''
template = Template(
textwrap.dedent(r"""
*pull request title*: ${pr_title}
%if data['pullrequest']['commits']:
*commits*: ${len(data['pullrequest']['commits'])}
%endif
'''))
text = render_with_traceback(
template,
pr_title=data['pullrequest']['title'],
data=data)
""")
)
text = render_with_traceback(template, pr_title=data["pullrequest"]["title"], data=data)
slack_data.title = title
slack_data.text = text
@ -203,12 +194,11 @@ class SlackDataHandler(CommitParsingDataHandler):
return slack_data
def format_repo_push_event(self, event, data, slack_data) -> SlackData:
branches_commits = self.aggregate_branch_data(
data['push']['branches'], data['push']['commits'])
branches_commits = self.aggregate_branch_data(data["push"]["branches"], data["push"]["commits"])
template = Template(r'''
template = Template(r"""
*${data['actor']['username']}* pushed to repo <${data['repo']['url']}|${data['repo']['repo_name']}>:
''')
""")
title = render_with_traceback(template, data=data)
text = render_with_traceback(
@ -224,18 +214,20 @@ class SlackDataHandler(CommitParsingDataHandler):
return slack_data
def format_repo_create_event(self, event, data, slack_data) -> SlackData:
template = Template(r'''
template = Template(r"""
*${data['actor']['username']}* created new repository ${data['repo']['repo_name']}:
''')
""")
title = render_with_traceback(template, data=data)
template = Template(textwrap.dedent(r'''
template = Template(
textwrap.dedent(r"""
repo_url: ${data['repo']['url']}
repo_type: ${data['repo']['repo_type']}
'''))
""")
)
text = render_with_traceback(template, data=data)
slack_data.title = title
slack_data.text = text
return slack_data
return slack_data

View file

@ -26,7 +26,7 @@ log = logging.getLogger(__name__)
class WebhookDataHandler(CommitParsingDataHandler):
name = 'webhook'
name = "webhook"
def __init__(self, template_url, headers):
self.template_url = template_url
@ -39,21 +39,21 @@ class WebhookDataHandler(CommitParsingDataHandler):
"""
# note: make sure to update the `WEBHOOK_URL_VARS` if this changes
common_vars = {
'repo_name': data['repo']['repo_name'],
'repo_type': data['repo']['repo_type'],
'repo_id': data['repo']['repo_id'],
'repo_url': data['repo']['url'],
'username': data['actor']['username'],
'user_id': data['actor']['user_id'],
'event_name': data['name']
"repo_name": data["repo"]["repo_name"],
"repo_type": data["repo"]["repo_type"],
"repo_id": data["repo"]["repo_id"],
"repo_url": data["repo"]["url"],
"username": data["actor"]["username"],
"user_id": data["actor"]["user_id"],
"event_name": data["name"],
}
extra_vars = {}
for extra_key, extra_val in data['repo']['extra_fields'].items():
extra_vars[f'extra__{extra_key}'] = extra_val
for extra_key, extra_val in data["repo"]["extra_fields"].items():
extra_vars[f"extra__{extra_key}"] = extra_val
common_vars.update(extra_vars)
template_url = self.template_url.replace('${extra:', '${extra__')
template_url = self.template_url.replace("${extra:", "${extra__")
for k, v in common_vars.items():
template_url = UrlTmpl(template_url).safe_substitute(**{k: v})
return template_url
@ -62,56 +62,49 @@ class WebhookDataHandler(CommitParsingDataHandler):
url = self.get_base_parsed_template(data)
url_calls = []
branches_commits = self.aggregate_branch_data(
data['push']['branches'], data['push']['commits'])
if '${branch}' in url or '${branch_head}' in url or '${commit_id}' in url:
branches_commits = self.aggregate_branch_data(data["push"]["branches"], data["push"]["commits"])
if "${branch}" in url or "${branch_head}" in url or "${commit_id}" in url:
# call it multiple times, for each branch if used in variables
for branch, commit_ids in branches_commits.items():
branch_url = UrlTmpl(url).safe_substitute(branch=branch)
if '${branch_head}' in branch_url:
if "${branch_head}" in branch_url:
# last commit in the aggregate is the head of the branch
branch_head = commit_ids['branch_head']
branch_head = commit_ids["branch_head"]
branch_url = UrlTmpl(branch_url).safe_substitute(branch_head=branch_head)
# call further down for each commit if used
if '${commit_id}' in branch_url:
for commit_data in commit_ids['commits']:
commit_id = commit_data['raw_id']
if "${commit_id}" in branch_url:
for commit_data in commit_ids["commits"]:
commit_id = commit_data["raw_id"]
commit_url = UrlTmpl(branch_url).safe_substitute(commit_id=commit_id)
# register per-commit call
log.debug(
'register %s call(%s) to url %s',
self.name, event, commit_url)
url_calls.append(
(commit_url, self.headers, data))
log.debug("register %s call(%s) to url %s", self.name, event, commit_url)
url_calls.append((commit_url, self.headers, data))
else:
# register per-branch call
log.debug('register %s call(%s) to url %s',
self.name, event, branch_url)
log.debug("register %s call(%s) to url %s", self.name, event, branch_url)
url_calls.append((branch_url, self.headers, data))
else:
log.debug('register %s call(%s) to url %s', self.name, event, url)
log.debug("register %s call(%s) to url %s", self.name, event, url)
url_calls.append((url, self.headers, data))
return url_calls
def repo_commit_comment_handler(self, event, data):
url = self.get_base_parsed_template(data)
log.debug('register %s call(%s) to url %s', self.name, event, url)
log.debug("register %s call(%s) to url %s", self.name, event, url)
comment_vars = [
('commit_comment_id', data['comment']['comment_id']),
('commit_comment_text', data['comment']['comment_text']),
('commit_comment_type', data['comment']['comment_type']),
('commit_comment_f_path', data['comment']['comment_f_path']),
('commit_comment_line_no', data['comment']['comment_line_no']),
('commit_comment_commit_id', data['commit']['commit_id']),
('commit_comment_commit_branch', data['commit']['commit_branch']),
('commit_comment_commit_message', data['commit']['commit_message']),
("commit_comment_id", data["comment"]["comment_id"]),
("commit_comment_text", data["comment"]["comment_text"]),
("commit_comment_type", data["comment"]["comment_type"]),
("commit_comment_f_path", data["comment"]["comment_f_path"]),
("commit_comment_line_no", data["comment"]["comment_line_no"]),
("commit_comment_commit_id", data["commit"]["commit_id"]),
("commit_comment_commit_branch", data["commit"]["commit_branch"]),
("commit_comment_commit_message", data["commit"]["commit_message"]),
]
for k, v in comment_vars:
url = UrlTmpl(url).safe_substitute(**{k: v})
@ -120,18 +113,16 @@ class WebhookDataHandler(CommitParsingDataHandler):
def repo_commit_comment_edit_handler(self, event, data):
url = self.get_base_parsed_template(data)
log.debug('register %s call(%s) to url %s', self.name, event, url)
log.debug("register %s call(%s) to url %s", self.name, event, url)
comment_vars = [
('commit_comment_id', data['comment']['comment_id']),
('commit_comment_text', data['comment']['comment_text']),
('commit_comment_type', data['comment']['comment_type']),
('commit_comment_f_path', data['comment']['comment_f_path']),
('commit_comment_line_no', data['comment']['comment_line_no']),
('commit_comment_commit_id', data['commit']['commit_id']),
('commit_comment_commit_branch', data['commit']['commit_branch']),
('commit_comment_commit_message', data['commit']['commit_message']),
("commit_comment_id", data["comment"]["comment_id"]),
("commit_comment_text", data["comment"]["comment_text"]),
("commit_comment_type", data["comment"]["comment_type"]),
("commit_comment_f_path", data["comment"]["comment_f_path"]),
("commit_comment_line_no", data["comment"]["comment_line_no"]),
("commit_comment_commit_id", data["commit"]["commit_id"]),
("commit_comment_commit_branch", data["commit"]["commit_branch"]),
("commit_comment_commit_message", data["commit"]["commit_message"]),
]
for k, v in comment_vars:
url = UrlTmpl(url).safe_substitute(**{k: v})
@ -140,18 +131,18 @@ class WebhookDataHandler(CommitParsingDataHandler):
def repo_create_event_handler(self, event, data):
url = self.get_base_parsed_template(data)
log.debug('register %s call(%s) to url %s', self.name, event, url)
log.debug("register %s call(%s) to url %s", self.name, event, url)
return [(url, self.headers, data)]
def pull_request_event_handler(self, event, data):
url = self.get_base_parsed_template(data)
log.debug('register %s call(%s) to url %s', self.name, event, url)
log.debug("register %s call(%s) to url %s", self.name, event, url)
pr_vars = [
('pull_request_id', data['pullrequest']['pull_request_id']),
('pull_request_title', data['pullrequest']['title']),
('pull_request_url', data['pullrequest']['url']),
('pull_request_shadow_url', data['pullrequest']['shadow_url']),
('pull_request_commits_uid', data['pullrequest']['commits_uid']),
("pull_request_id", data["pullrequest"]["pull_request_id"]),
("pull_request_title", data["pullrequest"]["title"]),
("pull_request_url", data["pullrequest"]["url"]),
("pull_request_shadow_url", data["pullrequest"]["shadow_url"]),
("pull_request_commits_uid", data["pullrequest"]["commits_uid"]),
]
for k, v in pr_vars:
url = UrlTmpl(url).safe_substitute(**{k: v})
@ -159,7 +150,6 @@ class WebhookDataHandler(CommitParsingDataHandler):
return [(url, self.headers, data)]
def __call__(self, event, data):
if isinstance(event, events.RepoPushEvent):
return self.repo_push_event_handler(event, data)
elif isinstance(event, events.RepoCreateEvent):
@ -171,5 +161,4 @@ class WebhookDataHandler(CommitParsingDataHandler):
elif isinstance(event, events.PullRequestEvent):
return self.pull_request_event_handler(event, data)
else:
raise ValueError(
f'event type `{event.__class__}` has no handler defined')
raise ValueError(f"event type `{event.__class__}` has no handler defined")

View file

@ -17,11 +17,10 @@
# and proprietary license terms, please see https://rhodecode.com/licenses/
import time
import logging
import deform # noqa
import deform # noqa
import deform.widget
import colander
@ -45,59 +44,55 @@ log = logging.getLogger(__name__)
class SlackSettingsSchema(colander.Schema):
service = colander.SchemaNode(
colander.String(),
title=_('Slack service URL'),
description=h.literal(_(
'This can be setup at the '
'<a href="https://my.slack.com/services/new/incoming-webhook/">'
'slack app manager</a>')),
default='',
title=_("Slack service URL"),
description=h.literal(
_(
"This can be setup at the "
'<a href="https://my.slack.com/services/new/incoming-webhook/">'
"slack app manager</a>"
)
),
default="",
preparer=strip_whitespace,
validator=colander.url,
widget=deform.widget.TextInputWidget(
placeholder='https://hooks.slack.com/services/...',
placeholder="https://hooks.slack.com/services/...",
),
)
username = colander.SchemaNode(
colander.String(),
title=_('Username'),
description=_('Username to show notifications coming from.'),
missing='Rhodecode',
title=_("Username"),
description=_("Username to show notifications coming from."),
missing="Rhodecode",
preparer=strip_whitespace,
widget=deform.widget.TextInputWidget(
placeholder='Rhodecode'
),
widget=deform.widget.TextInputWidget(placeholder="Rhodecode"),
)
channel = colander.SchemaNode(
colander.String(),
title=_('Channel'),
description=_('Channel to send notifications to.'),
missing='',
title=_("Channel"),
description=_("Channel to send notifications to."),
missing="",
preparer=strip_whitespace,
widget=deform.widget.TextInputWidget(
placeholder='#general'
),
widget=deform.widget.TextInputWidget(placeholder="#general"),
)
icon_emoji = colander.SchemaNode(
colander.String(),
title=_('Emoji'),
description=_('Emoji to use eg. :studio_microphone:'),
missing='',
title=_("Emoji"),
description=_("Emoji to use eg. :studio_microphone:"),
missing="",
preparer=strip_whitespace,
widget=deform.widget.TextInputWidget(
placeholder=':studio_microphone:'
),
widget=deform.widget.TextInputWidget(placeholder=":studio_microphone:"),
)
class SlackIntegrationType(IntegrationTypeBase):
key = 'slack'
display_name = _('Slack')
description = _('Send events such as repo pushes and pull requests to '
'your slack channel.')
key = "slack"
display_name = _("Slack")
description = _("Send events such as repo pushes and pull requests to your slack channel.")
@classmethod
def icon(cls):
return '''<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg viewBox="0 0 256 256" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid"><g><path d="M165.963541,15.8384262 C162.07318,3.86308197 149.212328,-2.69009836 137.239082,1.20236066 C125.263738,5.09272131 118.710557,17.9535738 122.603016,29.9268197 L181.550164,211.292328 C185.597902,222.478689 197.682361,228.765377 209.282098,225.426885 C221.381246,221.943607 228.756984,209.093246 224.896,197.21023 C224.749115,196.756984 165.963541,15.8384262 165.963541,15.8384262" fill="#DFA22F"></path><path d="M74.6260984,45.515541 C70.7336393,33.5422951 57.8727869,26.9891148 45.899541,30.8794754 C33.9241967,34.7698361 27.3710164,47.6306885 31.2634754,59.6060328 L90.210623,240.971541 C94.2583607,252.157902 106.34282,258.44459 117.942557,255.104 C130.041705,251.62282 137.417443,238.772459 133.556459,226.887344 C133.409574,226.436197 74.6260984,45.515541 74.6260984,45.515541" fill="#3CB187"></path><path d="M240.161574,166.045377 C252.136918,162.155016 258.688,149.294164 254.797639,137.31882 C250.907279,125.345574 238.046426,118.792393 226.07318,122.682754 L44.7076721,181.632 C33.5213115,185.677639 27.234623,197.762098 30.5731148,209.361836 C34.0563934,221.460984 46.9067541,228.836721 58.7897705,224.975738 C59.2430164,224.828852 240.161574,166.045377 240.161574,166.045377" fill="#CE1E5B"></path><path d="M82.507541,217.270557 C94.312918,213.434754 109.528131,208.491016 125.855475,203.186361 C122.019672,191.380984 117.075934,176.163672 111.76918,159.83423 L68.4191475,173.924721 L82.507541,217.270557" fill="#392538"></path><path d="M173.847082,187.591344 C190.235279,182.267803 205.467279,177.31777 217.195016,173.507148 C213.359213,161.70177 208.413377,146.480262 203.106623,130.146623 L159.75659,144.237115 L173.847082,187.591344" fill="#BB242A"></path><path d="M210.484459,74.7058361 C222.457705,70.8154754 229.010885,57.954623 225.120525,45.9792787 C221.230164,34.0060328 208.369311,27.4528525 196.393967,31.3432131 L15.028459,90.292459 C3.84209836,94.3380984 -2.44459016,106.422557 0.896,118.022295 C4.37718033,130.121443 17.227541,137.49718 29.1126557,133.636197 C29.5638033,133.489311 210.484459,74.7058361 210.484459,74.7058361" fill="#72C5CD"></path><path d="M52.8220328,125.933115 C64.6274098,122.097311 79.8468197,117.151475 96.1762623,111.84682 C90.8527213,95.4565246 85.9026885,80.2245246 82.0920656,68.4946885 L38.731541,82.5872787 L52.8220328,125.933115" fill="#248C73"></path><path d="M144.159475,96.256 C160.551869,90.9303607 175.785967,85.9803279 187.515803,82.1676066 C182.190164,65.7752131 177.240131,50.5390164 173.42741,38.807082 L130.068984,52.8996721 L144.159475,96.256" fill="#62803A"></path></g></svg>'''
return """<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg viewBox="0 0 256 256" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid"><g><path d="M165.963541,15.8384262 C162.07318,3.86308197 149.212328,-2.69009836 137.239082,1.20236066 C125.263738,5.09272131 118.710557,17.9535738 122.603016,29.9268197 L181.550164,211.292328 C185.597902,222.478689 197.682361,228.765377 209.282098,225.426885 C221.381246,221.943607 228.756984,209.093246 224.896,197.21023 C224.749115,196.756984 165.963541,15.8384262 165.963541,15.8384262" fill="#DFA22F"></path><path d="M74.6260984,45.515541 C70.7336393,33.5422951 57.8727869,26.9891148 45.899541,30.8794754 C33.9241967,34.7698361 27.3710164,47.6306885 31.2634754,59.6060328 L90.210623,240.971541 C94.2583607,252.157902 106.34282,258.44459 117.942557,255.104 C130.041705,251.62282 137.417443,238.772459 133.556459,226.887344 C133.409574,226.436197 74.6260984,45.515541 74.6260984,45.515541" fill="#3CB187"></path><path d="M240.161574,166.045377 C252.136918,162.155016 258.688,149.294164 254.797639,137.31882 C250.907279,125.345574 238.046426,118.792393 226.07318,122.682754 L44.7076721,181.632 C33.5213115,185.677639 27.234623,197.762098 30.5731148,209.361836 C34.0563934,221.460984 46.9067541,228.836721 58.7897705,224.975738 C59.2430164,224.828852 240.161574,166.045377 240.161574,166.045377" fill="#CE1E5B"></path><path d="M82.507541,217.270557 C94.312918,213.434754 109.528131,208.491016 125.855475,203.186361 C122.019672,191.380984 117.075934,176.163672 111.76918,159.83423 L68.4191475,173.924721 L82.507541,217.270557" fill="#392538"></path><path d="M173.847082,187.591344 C190.235279,182.267803 205.467279,177.31777 217.195016,173.507148 C213.359213,161.70177 208.413377,146.480262 203.106623,130.146623 L159.75659,144.237115 L173.847082,187.591344" fill="#BB242A"></path><path d="M210.484459,74.7058361 C222.457705,70.8154754 229.010885,57.954623 225.120525,45.9792787 C221.230164,34.0060328 208.369311,27.4528525 196.393967,31.3432131 L15.028459,90.292459 C3.84209836,94.3380984 -2.44459016,106.422557 0.896,118.022295 C4.37718033,130.121443 17.227541,137.49718 29.1126557,133.636197 C29.5638033,133.489311 210.484459,74.7058361 210.484459,74.7058361" fill="#72C5CD"></path><path d="M52.8220328,125.933115 C64.6274098,122.097311 79.8468197,117.151475 96.1762623,111.84682 C90.8527213,95.4565246 85.9026885,80.2245246 82.0920656,68.4946885 L38.731541,82.5872787 L52.8220328,125.933115" fill="#248C73"></path><path d="M144.159475,96.256 C160.551869,90.9303607 175.785967,85.9803279 187.515803,82.1676066 C182.190164,65.7752131 177.240131,50.5390164 173.42741,38.807082 L130.068984,52.8996721 L144.159475,96.256" fill="#62803A"></path></g></svg>"""
valid_events = [
events.PullRequestCloseEvent,
@ -112,24 +107,24 @@ class SlackIntegrationType(IntegrationTypeBase):
def settings_schema(self):
schema = SlackSettingsSchema()
schema.add(colander.SchemaNode(
colander.Set(),
widget=CheckboxChoiceWidgetDesc(
values=sorted(
[(e.name, e.display_name, e.description) for e in self.valid_events]
schema.add(
colander.SchemaNode(
colander.Set(),
widget=CheckboxChoiceWidgetDesc(
values=sorted([(e.name, e.display_name, e.description) for e in self.valid_events]),
),
),
description="List of events activated for this integration",
name='events'
))
description="List of events activated for this integration",
name="events",
)
)
return schema
def send_event(self, event):
log.debug('handling event %s with integration %s', event.name, self)
log.debug("handling event %s with integration %s", event.name, self)
if event.__class__ not in self.valid_events:
log.debug('event %r not present in valid event list (%s)', event, self.valid_events)
log.debug("event %r not present in valid event list (%s)", event, self.valid_events)
return
if not self.event_enabled(event):
@ -154,36 +149,36 @@ def post_text_to_slack(settings, slack_data: SlackData):
fields = slack_data.fields
overrides = slack_data.overrides
log.debug('sending %s (%s) to slack %s', title, text, settings['service'])
log.debug("sending %s (%s) to slack %s", title, text, settings["service"])
fields = fields or []
overrides = overrides or {}
message_data = {
"fallback": text,
"color": "#427cc9",
"pretext": title,
#"author_name": "Bobby Tables",
#"author_link": "http://flickr.com/bobby/",
#"author_icon": "http://flickr.com/icons/bobby.jpg",
#"title": "Slack API Documentation",
#"title_link": "https://api.slack.com/",
"text": text,
"fields": fields,
#"image_url": "http://my-website.com/path/to/image.jpg",
#"thumb_url": "http://example.com/path/to/thumb.png",
"footer": "RhodeCode",
#"footer_icon": "",
"ts": time.time(),
"mrkdwn_in": ["pretext", "text"]
"fallback": text,
"color": "#427cc9",
"pretext": title,
# "author_name": "Bobby Tables",
# "author_link": "http://flickr.com/bobby/",
# "author_icon": "http://flickr.com/icons/bobby.jpg",
# "title": "Slack API Documentation",
# "title_link": "https://api.slack.com/",
"text": text,
"fields": fields,
# "image_url": "http://my-website.com/path/to/image.jpg",
# "thumb_url": "http://example.com/path/to/thumb.png",
"footer": "RhodeCode",
# "footer_icon": "",
"ts": time.time(),
"mrkdwn_in": ["pretext", "text"],
}
message_data.update(overrides)
json_message = {
"icon_emoji": settings.get('icon_emoji', ':studio_microphone:'),
"channel": settings.get('channel', ''),
"username": settings.get('username', 'Rhodecode'),
"attachments": [message_data]
"icon_emoji": settings.get("icon_emoji", ":studio_microphone:"),
"channel": settings.get("channel", ""),
"username": settings.get("username", "Rhodecode"),
"attachments": [message_data],
}
req_session = requests_retry_call()
resp = req_session.post(settings['service'], json=json_message, timeout=60)
resp = req_session.post(settings["service"], json=json_message, timeout=60)
resp.raise_for_status() # raise exception on a failed request

View file

@ -17,7 +17,7 @@
# and proprietary license terms, please see https://rhodecode.com/licenses/
import deform # noqa
import deform # noqa
import deform.widget
import logging
import colander
@ -50,98 +50,91 @@ URL_VARS = get_url_vars(WEBHOOK_URL_VARS)
class WebhookSettingsSchema(colander.Schema):
url = colander.SchemaNode(
colander.String(),
title=_('Webhook URL'),
description=
_('URL to which Webhook should submit data. If used some of the '
'variables would trigger multiple calls, like ${branch} or '
'${commit_id}. Webhook will be called as many times as unique '
'objects in data in such cases.'),
title=_("Webhook URL"),
description=_(
"URL to which Webhook should submit data. If used some of the "
"variables would trigger multiple calls, like ${branch} or "
"${commit_id}. Webhook will be called as many times as unique "
"objects in data in such cases."
),
missing=colander.required,
required=True,
preparer=strip_whitespace,
validator=colander.url,
widget=widgets.CodeMirrorWidget(
help_block_collapsable_name='Show url variables',
help_block_collapsable_name="Show url variables",
help_block_collapsable=(
'E.g https://my-serv.com/trigger_job/${{event_name}}'
'?PR_ID=${{pull_request_id}}'
'\nFull list of vars:\n{}'.format(URL_VARS)),
codemirror_mode='text',
codemirror_options='{"lineNumbers": false, "lineWrapping": true}'),
"E.g https://my-serv.com/trigger_job/${{event_name}}"
"?PR_ID=${{pull_request_id}}"
"\nFull list of vars:\n{}".format(URL_VARS)
),
codemirror_mode="text",
codemirror_options='{"lineNumbers": false, "lineWrapping": true}',
),
)
secret_token = colander.SchemaNode(
colander.String(),
title=_('Secret Token'),
description=_('Optional string used to validate received payloads. '
'It will be sent together with event data in JSON'),
default='',
missing='',
widget=deform.widget.TextInputWidget(
placeholder='e.g. secret_token'
title=_("Secret Token"),
description=_(
"Optional string used to validate received payloads. It will be sent together with event data in JSON"
),
default="",
missing="",
widget=deform.widget.TextInputWidget(placeholder="e.g. secret_token"),
)
username = colander.SchemaNode(
colander.String(),
title=_('Username'),
description=_('Optional username to authenticate the call.'),
default='',
missing='',
widget=deform.widget.TextInputWidget(
placeholder='e.g. admin'
),
title=_("Username"),
description=_("Optional username to authenticate the call."),
default="",
missing="",
widget=deform.widget.TextInputWidget(placeholder="e.g. admin"),
)
password = colander.SchemaNode(
colander.String(),
title=_('Password'),
description=_('Optional password to authenticate the call.'),
default='',
missing='',
title=_("Password"),
description=_("Optional password to authenticate the call."),
default="",
missing="",
widget=deform.widget.PasswordWidget(
placeholder='e.g. secret.',
placeholder="e.g. secret.",
redisplay=True,
),
)
custom_header_key = colander.SchemaNode(
colander.String(),
title=_('Custom Header Key'),
description=_('Custom Header name to be set when calling endpoint.'),
default='',
missing='',
widget=deform.widget.TextInputWidget(
placeholder='e.g: Authorization'
),
title=_("Custom Header Key"),
description=_("Custom Header name to be set when calling endpoint."),
default="",
missing="",
widget=deform.widget.TextInputWidget(placeholder="e.g: Authorization"),
)
custom_header_val = colander.SchemaNode(
colander.String(),
title=_('Custom Header Value'),
description=_('Custom Header value to be set when calling endpoint.'),
default='',
missing='',
widget=deform.widget.TextInputWidget(
placeholder='e.g. Basic XxXxXx'
),
title=_("Custom Header Value"),
description=_("Custom Header value to be set when calling endpoint."),
default="",
missing="",
widget=deform.widget.TextInputWidget(placeholder="e.g. Basic XxXxXx"),
)
method_type = colander.SchemaNode(
colander.String(),
title=_('Call Method'),
description=_('Select a HTTP method to use when calling the Webhook.'),
default='post',
missing='',
widget=deform.widget.RadioChoiceWidget(
values=[('get', 'GET'), ('post', 'POST'), ('put', 'PUT')],
inline=True
),
title=_("Call Method"),
description=_("Select a HTTP method to use when calling the Webhook."),
default="post",
missing="",
widget=deform.widget.RadioChoiceWidget(values=[("get", "GET"), ("post", "POST"), ("put", "PUT")], inline=True),
)
class WebhookIntegrationType(IntegrationTypeBase):
key = 'webhook'
display_name = _('Webhook')
description = _('send JSON data to a url endpoint')
key = "webhook"
display_name = _("Webhook")
description = _("send JSON data to a url endpoint")
@classmethod
def icon(cls):
return '''<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg viewBox="0 0 256 239" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid"><g><path d="M119.540432,100.502743 C108.930124,118.338815 98.7646301,135.611455 88.3876025,152.753617 C85.7226696,157.154315 84.4040417,160.738531 86.5332204,166.333309 C92.4107024,181.787152 84.1193605,196.825836 68.5350381,200.908244 C53.8383677,204.759349 39.5192953,195.099955 36.6032893,179.365384 C34.0194114,165.437749 44.8274148,151.78491 60.1824106,149.608284 C61.4694072,149.424428 62.7821041,149.402681 64.944891,149.240571 C72.469175,136.623655 80.1773157,123.700312 88.3025935,110.073173 C73.611854,95.4654658 64.8677898,78.3885437 66.803227,57.2292132 C68.1712787,42.2715849 74.0527146,29.3462646 84.8033863,18.7517722 C105.393354,-1.53572199 136.805164,-4.82141828 161.048542,10.7510424 C184.333097,25.7086706 194.996783,54.8450075 185.906752,79.7822957 C179.052655,77.9239597 172.151111,76.049808 164.563565,73.9917997 C167.418285,60.1274266 165.306899,47.6765751 155.95591,37.0109123 C149.777932,29.9690049 141.850349,26.2780332 132.835442,24.9178894 C114.764113,22.1877169 97.0209573,33.7983633 91.7563309,51.5355878 C85.7800012,71.6669027 94.8245623,88.1111998 119.540432,100.502743 L119.540432,100.502743 Z" fill="#C73A63"></path><path d="M149.841194,79.4106285 C157.316054,92.5969067 164.905578,105.982857 172.427885,119.246236 C210.44865,107.483365 239.114472,128.530009 249.398582,151.063322 C261.81978,178.282014 253.328765,210.520191 228.933162,227.312431 C203.893073,244.551464 172.226236,241.605803 150.040866,219.46195 C155.694953,214.729124 161.376716,209.974552 167.44794,204.895759 C189.360489,219.088306 208.525074,218.420096 222.753207,201.614016 C234.885769,187.277151 234.622834,165.900356 222.138374,151.863988 C207.730339,135.66681 188.431321,135.172572 165.103273,150.721309 C155.426087,133.553447 145.58086,116.521995 136.210101,99.2295848 C133.05093,93.4015266 129.561608,90.0209366 122.440622,88.7873178 C110.547271,86.7253555 102.868785,76.5124151 102.408155,65.0698097 C101.955433,53.7537294 108.621719,43.5249733 119.04224,39.5394355 C129.363912,35.5914599 141.476705,38.7783085 148.419765,47.554004 C154.093621,54.7244134 155.896602,62.7943365 152.911402,71.6372484 C152.081082,74.1025091 151.00562,76.4886916 149.841194,79.4106285 L149.841194,79.4106285 Z" fill="#4B4B4B"></path><path d="M167.706921,187.209935 L121.936499,187.209935 C117.54964,205.253587 108.074103,219.821756 91.7464461,229.085759 C79.0544063,236.285822 65.3738898,238.72736 50.8136292,236.376762 C24.0061432,232.053165 2.08568567,207.920497 0.156179306,180.745298 C-2.02835403,149.962159 19.1309765,122.599149 47.3341915,116.452801 C49.2814904,123.524363 51.2485589,130.663141 53.1958579,137.716911 C27.3195169,150.919004 18.3639187,167.553089 25.6054984,188.352614 C31.9811726,206.657224 50.0900643,216.690262 69.7528413,212.809503 C89.8327554,208.847688 99.9567329,192.160226 98.7211371,165.37844 C117.75722,165.37844 136.809118,165.180745 155.847178,165.475311 C163.280522,165.591951 169.019617,164.820939 174.620326,158.267339 C183.840836,147.48306 200.811003,148.455721 210.741239,158.640984 C220.88894,169.049642 220.402609,185.79839 209.663799,195.768166 C199.302587,205.38802 182.933414,204.874012 173.240413,194.508846 C171.247644,192.37176 169.677943,189.835329 167.706921,187.209935 L167.706921,187.209935 Z" fill="#4A4A4A"></path></g></svg>'''
return """<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg viewBox="0 0 256 239" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid"><g><path d="M119.540432,100.502743 C108.930124,118.338815 98.7646301,135.611455 88.3876025,152.753617 C85.7226696,157.154315 84.4040417,160.738531 86.5332204,166.333309 C92.4107024,181.787152 84.1193605,196.825836 68.5350381,200.908244 C53.8383677,204.759349 39.5192953,195.099955 36.6032893,179.365384 C34.0194114,165.437749 44.8274148,151.78491 60.1824106,149.608284 C61.4694072,149.424428 62.7821041,149.402681 64.944891,149.240571 C72.469175,136.623655 80.1773157,123.700312 88.3025935,110.073173 C73.611854,95.4654658 64.8677898,78.3885437 66.803227,57.2292132 C68.1712787,42.2715849 74.0527146,29.3462646 84.8033863,18.7517722 C105.393354,-1.53572199 136.805164,-4.82141828 161.048542,10.7510424 C184.333097,25.7086706 194.996783,54.8450075 185.906752,79.7822957 C179.052655,77.9239597 172.151111,76.049808 164.563565,73.9917997 C167.418285,60.1274266 165.306899,47.6765751 155.95591,37.0109123 C149.777932,29.9690049 141.850349,26.2780332 132.835442,24.9178894 C114.764113,22.1877169 97.0209573,33.7983633 91.7563309,51.5355878 C85.7800012,71.6669027 94.8245623,88.1111998 119.540432,100.502743 L119.540432,100.502743 Z" fill="#C73A63"></path><path d="M149.841194,79.4106285 C157.316054,92.5969067 164.905578,105.982857 172.427885,119.246236 C210.44865,107.483365 239.114472,128.530009 249.398582,151.063322 C261.81978,178.282014 253.328765,210.520191 228.933162,227.312431 C203.893073,244.551464 172.226236,241.605803 150.040866,219.46195 C155.694953,214.729124 161.376716,209.974552 167.44794,204.895759 C189.360489,219.088306 208.525074,218.420096 222.753207,201.614016 C234.885769,187.277151 234.622834,165.900356 222.138374,151.863988 C207.730339,135.66681 188.431321,135.172572 165.103273,150.721309 C155.426087,133.553447 145.58086,116.521995 136.210101,99.2295848 C133.05093,93.4015266 129.561608,90.0209366 122.440622,88.7873178 C110.547271,86.7253555 102.868785,76.5124151 102.408155,65.0698097 C101.955433,53.7537294 108.621719,43.5249733 119.04224,39.5394355 C129.363912,35.5914599 141.476705,38.7783085 148.419765,47.554004 C154.093621,54.7244134 155.896602,62.7943365 152.911402,71.6372484 C152.081082,74.1025091 151.00562,76.4886916 149.841194,79.4106285 L149.841194,79.4106285 Z" fill="#4B4B4B"></path><path d="M167.706921,187.209935 L121.936499,187.209935 C117.54964,205.253587 108.074103,219.821756 91.7464461,229.085759 C79.0544063,236.285822 65.3738898,238.72736 50.8136292,236.376762 C24.0061432,232.053165 2.08568567,207.920497 0.156179306,180.745298 C-2.02835403,149.962159 19.1309765,122.599149 47.3341915,116.452801 C49.2814904,123.524363 51.2485589,130.663141 53.1958579,137.716911 C27.3195169,150.919004 18.3639187,167.553089 25.6054984,188.352614 C31.9811726,206.657224 50.0900643,216.690262 69.7528413,212.809503 C89.8327554,208.847688 99.9567329,192.160226 98.7211371,165.37844 C117.75722,165.37844 136.809118,165.180745 155.847178,165.475311 C163.280522,165.591951 169.019617,164.820939 174.620326,158.267339 C183.840836,147.48306 200.811003,148.455721 210.741239,158.640984 C220.88894,169.049642 220.402609,185.79839 209.663799,195.768166 C199.302587,205.38802 182.933414,204.874012 173.240413,194.508846 C171.247644,192.37176 169.677943,189.835329 167.706921,187.209935 L167.706921,187.209935 Z" fill="#4A4A4A"></path></g></svg>"""
valid_events = [
events.PullRequestCloseEvent,
@ -159,41 +152,41 @@ class WebhookIntegrationType(IntegrationTypeBase):
def settings_schema(self):
schema = WebhookSettingsSchema()
schema.add(colander.SchemaNode(
colander.Set(),
widget=CheckboxChoiceWidgetDesc(
values=sorted(
[(e.name, e.display_name, e.description) for e in self.valid_events]
schema.add(
colander.SchemaNode(
colander.Set(),
widget=CheckboxChoiceWidgetDesc(
values=sorted([(e.name, e.display_name, e.description) for e in self.valid_events]),
),
),
description="List of events activated for this integration",
name='events'
))
description="List of events activated for this integration",
name="events",
)
)
return schema
def send_event(self, event):
log.debug('handling event %s with integration %s', event.name, self)
log.debug("handling event %s with integration %s", event.name, self)
if event.__class__ not in self.valid_events:
log.debug('event %r not present in valid event list (%s)', event, self.valid_events)
log.debug("event %r not present in valid event list (%s)", event, self.valid_events)
return
if not self.event_enabled(event):
return
data = event.as_dict()
template_url = self.settings['url']
template_url = self.settings["url"]
headers = {}
head_key = self.settings.get('custom_header_key')
head_val = self.settings.get('custom_header_val')
head_key = self.settings.get("custom_header_key")
head_val = self.settings.get("custom_header_val")
if head_key and head_val:
headers = {head_key: head_val}
handler = WebhookDataHandler(template_url, headers)
url_calls = handler(event, data)
log.debug('Webhook: calling following urls: %s', [x[0] for x in url_calls])
log.debug("Webhook: calling following urls: %s", [x[0] for x in url_calls])
run_task(post_to_webhook, self.settings, url_calls)
@ -239,7 +232,7 @@ def post_to_webhook(settings, url_calls):
"""
call_headers = {
'User-Agent': f'RhodeCode-webhook-caller/{rhodecode.__version__}'
"User-Agent": f"RhodeCode-webhook-caller/{rhodecode.__version__}"
} # updated below with custom ones, allows override
auth = get_auth(settings)
@ -248,20 +241,17 @@ def post_to_webhook(settings, url_calls):
for url, headers, data in url_calls:
req_session = requests_retry_call()
method = settings.get('method_type') or 'post'
method = settings.get("method_type") or "post"
call_method = getattr(req_session, method)
headers = headers or {}
call_headers.update(headers)
log.debug('calling Webhook with method: %s, and auth:%s', call_method, auth)
if settings.get('log_data'):
log.debug('calling webhook with data: %s', data)
resp = call_method(url, json={
'token': token,
'event': data
}, headers=call_headers, auth=auth, timeout=60)
log.debug('Got Webhook response: %s', resp)
log.debug("calling Webhook with method: %s, and auth:%s", call_method, auth)
if settings.get("log_data"):
log.debug("calling webhook with data: %s", data)
resp = call_method(url, json={"token": token, "event": data}, headers=call_headers, auth=auth, timeout=60)
log.debug("Got Webhook response: %s", resp)
try:
resp.raise_for_status() # raise exception on a failed request

View file

@ -26,16 +26,19 @@ from rhodecode.integrations import integration_type_registry
from rhodecode.apps._base import BaseAppView
from rhodecode.apps._base.navigation import navigation_list
from rhodecode.lib.auth import (
LoginRequired, CSRFRequired, HasPermissionAnyDecorator,
HasRepoPermissionAnyDecorator, HasRepoGroupPermissionAnyDecorator)
LoginRequired,
CSRFRequired,
HasPermissionAnyDecorator,
HasRepoPermissionAnyDecorator,
HasRepoGroupPermissionAnyDecorator,
)
from rhodecode.lib.utils2 import safe_int
from rhodecode.lib.helpers import Page
from rhodecode.lib import helpers as h
from rhodecode.model.db import Repository, RepoGroup, Session, Integration
from rhodecode.model.scm import ScmModel
from rhodecode.model.integration import IntegrationModel
from rhodecode.model.validation_schema.schemas.integration_schema import (
make_integration_schema, IntegrationScopeType)
from rhodecode.model.validation_schema.schemas.integration_schema import make_integration_schema, IntegrationScopeType
log = logging.getLogger(__name__)
@ -64,16 +67,16 @@ class IntegrationSettingsViewBase(BaseAppView):
request = self.request
if 'repo_name' in request.matchdict: # in repo settings context
repo_name = request.matchdict['repo_name']
if "repo_name" in request.matchdict: # in repo settings context
repo_name = request.matchdict["repo_name"]
self.repo = Repository.get_by_repo_name(repo_name)
if 'repo_group_name' in request.matchdict: # in group settings context
repo_group_name = request.matchdict['repo_group_name']
if "repo_group_name" in request.matchdict: # in group settings context
repo_group_name = request.matchdict["repo_group_name"]
self.repo_group = RepoGroup.get_by_group_name(repo_group_name)
if 'integration' in request.matchdict: # integration type context
integration_type = request.matchdict['integration']
if "integration" in request.matchdict: # integration type context
integration_type = request.matchdict["integration"]
if integration_type not in integration_type_registry:
raise HTTPNotFound()
@ -81,8 +84,8 @@ class IntegrationSettingsViewBase(BaseAppView):
if self.IntegrationType.is_dummy:
raise HTTPNotFound()
if 'integration_id' in request.matchdict: # single integration context
integration_id = request.matchdict['integration_id']
if "integration_id" in request.matchdict: # single integration context
integration_id = request.matchdict["integration_id"]
self.integration = Integration.get(integration_id)
# extra perms check just in case
@ -95,69 +98,60 @@ class IntegrationSettingsViewBase(BaseAppView):
def _has_perms_for_integration(self, integration):
perms = self.request.user.permissions
if 'hg.admin' in perms['global']:
if "hg.admin" in perms["global"]:
return True
if integration.repo:
return perms['repositories'].get(
integration.repo.repo_name) == 'repository.admin'
return perms["repositories"].get(integration.repo.repo_name) == "repository.admin"
if integration.repo_group:
return perms['repositories_groups'].get(
integration.repo_group.group_name) == 'group.admin'
return perms["repositories_groups"].get(integration.repo_group.group_name) == "group.admin"
return False
def _get_local_tmpl_context(self, include_app_defaults=True):
_ = self.request.translate
c = super()._get_local_tmpl_context(
include_app_defaults=include_app_defaults)
c.active = 'integrations'
c = super()._get_local_tmpl_context(include_app_defaults=include_app_defaults)
c.active = "integrations"
return c
def _form_schema(self):
schema = make_integration_schema(IntegrationType=self.IntegrationType,
settings=self.settings)
schema = make_integration_schema(IntegrationType=self.IntegrationType, settings=self.settings)
# returns a clone, important if mutating the schema later
return schema.bind(
permissions=self.request.user.permissions,
no_scope=not self.admin_view)
return schema.bind(permissions=self.request.user.permissions, no_scope=not self.admin_view)
def _form_defaults(self):
_ = self.request.translate
defaults = {}
if self.integration:
defaults['settings'] = self.integration.settings or {}
defaults['options'] = {
'name': self.integration.name,
'enabled': self.integration.enabled,
'scope': {
'repo': self.integration.repo,
'repo_group': self.integration.repo_group,
'child_repos_only': self.integration.child_repos_only,
defaults["settings"] = self.integration.settings or {}
defaults["options"] = {
"name": self.integration.name,
"enabled": self.integration.enabled,
"scope": {
"repo": self.integration.repo,
"repo_group": self.integration.repo_group,
"child_repos_only": self.integration.child_repos_only,
},
}
else:
if self.repo:
scope = _('{repo_name} repository').format(
repo_name=self.repo.repo_name)
scope = _("{repo_name} repository").format(repo_name=self.repo.repo_name)
elif self.repo_group:
scope = _('{repo_group_name} repo group').format(
repo_group_name=self.repo_group.group_name)
scope = _("{repo_group_name} repo group").format(repo_group_name=self.repo_group.group_name)
else:
scope = _('Global')
scope = _("Global")
defaults['options'] = {
'enabled': True,
'name': _('{name} integration').format(
name=self.IntegrationType.display_name),
defaults["options"] = {
"enabled": True,
"name": _("{name} integration").format(name=self.IntegrationType.display_name),
}
defaults['options']['scope'] = {
'repo': self.repo,
'repo_group': self.repo_group,
defaults["options"]["scope"] = {
"repo": self.repo,
"repo_group": self.repo_group,
}
return defaults
@ -167,23 +161,22 @@ class IntegrationSettingsViewBase(BaseAppView):
Session().delete(integration)
Session().commit()
h.flash(
_('Integration {integration_name} deleted successfully.').format(
integration_name=integration.name),
category='success')
_("Integration {integration_name} deleted successfully.").format(integration_name=integration.name),
category="success",
)
if self.repo:
redirect_to = self.request.route_path(
'repo_integrations_home', repo_name=self.repo.repo_name)
redirect_to = self.request.route_path("repo_integrations_home", repo_name=self.repo.repo_name)
elif self.repo_group:
redirect_to = self.request.route_path(
'repo_group_integrations_home',
repo_group_name=self.repo_group.group_name)
"repo_group_integrations_home", repo_group_name=self.repo_group.group_name
)
else:
redirect_to = self.request.route_path('global_integrations_home')
redirect_to = self.request.route_path("global_integrations_home")
raise HTTPFound(redirect_to)
def _integration_list(self):
""" List integrations """
"""List integrations"""
c = self.load_default_context()
if self.repo:
@ -191,44 +184,39 @@ class IntegrationSettingsViewBase(BaseAppView):
elif self.repo_group:
scope = self.repo_group
else:
scope = 'all'
scope = "all"
integrations = []
for IntType, integration in IntegrationModel().get_integrations(
scope=scope, IntegrationType=self.IntegrationType):
scope=scope, IntegrationType=self.IntegrationType
):
# extra permissions check *just in case*
if not self._has_perms_for_integration(integration):
continue
integrations.append((IntType, integration))
sort_arg = self.request.GET.get('sort', 'name:asc')
sort_dir = 'asc'
if ':' in sort_arg:
sort_field, sort_dir = sort_arg.split(':')
sort_arg = self.request.GET.get("sort", "name:asc")
sort_dir = "asc"
if ":" in sort_arg:
sort_field, sort_dir = sort_arg.split(":")
else:
sort_field = sort_arg, 'asc'
sort_field = sort_arg, "asc"
assert sort_field in ('name', 'integration_type', 'enabled', 'scope')
assert sort_field in ("name", "integration_type", "enabled", "scope")
integrations.sort(
key=lambda x: getattr(x[1], sort_field),
reverse=(sort_dir == 'desc'))
integrations.sort(key=lambda x: getattr(x[1], sort_field), reverse=(sort_dir == "desc"))
def url_generator(page_num):
query_params = {
'page': page_num
}
query_params = {"page": page_num}
return self.request.current_route_path(_query=query_params)
page = safe_int(self.request.GET.get('page', 1), 1)
page = safe_int(self.request.GET.get("page", 1), 1)
integrations = Page(
integrations, page=page, items_per_page=10, url_maker=url_generator)
integrations = Page(integrations, page=page, items_per_page=10, url_maker=url_generator)
c.rev_sort_dir = sort_dir != 'desc' and 'desc' or 'asc'
c.rev_sort_dir = sort_dir != "desc" and "desc" or "asc"
c.current_IntegrationType = self.IntegrationType
c.integrations_list = integrations
@ -246,9 +234,9 @@ class IntegrationSettingsViewBase(BaseAppView):
schema = self._form_schema()
if self.integration:
buttons = ('submit', 'delete')
buttons = ("submit", "delete")
else:
buttons = ('submit',)
buttons = ("submit",)
form = form or deform.Form(schema, appstruct=defaults, buttons=buttons)
@ -267,42 +255,42 @@ class IntegrationSettingsViewBase(BaseAppView):
controls = list(self.request.POST.items())
pstruct = peppercorn.parse(controls)
if self.integration and pstruct.get('delete'):
if self.integration and pstruct.get("delete"):
return self._delete_integration(self.integration)
schema = self._form_schema()
skip_settings_validation = False
if self.integration and 'enabled' not in pstruct.get('options', {}):
if self.integration and "enabled" not in pstruct.get("options", {}):
skip_settings_validation = True
schema['settings'].validator = None
for field in schema['settings'].children:
schema["settings"].validator = None
for field in schema["settings"].children:
field.validator = None
field.missing = ''
field.missing = ""
if self.integration:
buttons = ('submit', 'delete')
buttons = ("submit", "delete")
else:
buttons = ('submit',)
buttons = ("submit",)
form = deform.Form(schema, buttons=buttons)
if not self.admin_view:
# scope is read only field in these cases, and has to be added
options = pstruct.setdefault('options', {})
if 'scope' not in options:
options['scope'] = IntegrationScopeType().serialize(None, {
'repo': self.repo,
'repo_group': self.repo_group,
})
options = pstruct.setdefault("options", {})
if "scope" not in options:
options["scope"] = IntegrationScopeType().serialize(
None,
{
"repo": self.repo,
"repo_group": self.repo_group,
},
)
try:
valid_data = form.validate_pstruct(pstruct)
except deform.ValidationFailure as e:
h.flash(
_('Errors exist when saving integration settings. '
'Please check the form inputs.'),
category='error')
h.flash(_("Errors exist when saving integration settings. Please check the form inputs."), category="error")
return self._settings_get(form=e)
if not self.integration:
@ -310,24 +298,27 @@ class IntegrationSettingsViewBase(BaseAppView):
self.integration.integration_type = self.IntegrationType.key
Session().add(self.integration)
scope = valid_data['options']['scope']
scope = valid_data["options"]["scope"]
IntegrationModel().update_integration(self.integration,
name=valid_data['options']['name'],
enabled=valid_data['options']['enabled'],
settings=valid_data['settings'],
repo=scope['repo'],
repo_group=scope['repo_group'],
child_repos_only=scope['child_repos_only'],
IntegrationModel().update_integration(
self.integration,
name=valid_data["options"]["name"],
enabled=valid_data["options"]["enabled"],
settings=valid_data["settings"],
repo=scope["repo"],
repo_group=scope["repo_group"],
child_repos_only=scope["child_repos_only"],
)
self.integration.settings = valid_data['settings']
self.integration.settings = valid_data["settings"]
Session().commit()
# Display success message and redirect.
h.flash(
_('Integration {integration_name} updated successfully.').format(
integration_name=self.IntegrationType.display_name),
category='success')
_("Integration {integration_name} updated successfully.").format(
integration_name=self.IntegrationType.display_name
),
category="success",
)
# if integration scope changes, we must redirect to the right place
# keeping in mind if the original view was for /repo/ or /_admin/
@ -335,21 +326,24 @@ class IntegrationSettingsViewBase(BaseAppView):
if self.integration.repo and not admin_view:
redirect_to = self.request.route_path(
'repo_integrations_edit',
"repo_integrations_edit",
repo_name=self.integration.repo.repo_name,
integration=self.integration.integration_type,
integration_id=self.integration.integration_id)
integration_id=self.integration.integration_id,
)
elif self.integration.repo_group and not admin_view:
redirect_to = self.request.route_path(
'repo_group_integrations_edit',
"repo_group_integrations_edit",
repo_group_name=self.integration.repo_group.group_name,
integration=self.integration.integration_type,
integration_id=self.integration.integration_id)
integration_id=self.integration.integration_id,
)
else:
redirect_to = self.request.route_path(
'global_integrations_edit',
"global_integrations_edit",
integration=self.integration.integration_type,
integration_id=self.integration.integration_id)
integration_id=self.integration.integration_id,
)
return HTTPFound(redirect_to)
@ -372,23 +366,23 @@ class GlobalIntegrationsView(IntegrationSettingsViewBase):
return c
@LoginRequired()
@HasPermissionAnyDecorator('hg.admin')
@HasPermissionAnyDecorator("hg.admin")
def integration_list(self):
return self._integration_list()
@LoginRequired()
@HasPermissionAnyDecorator('hg.admin')
@HasPermissionAnyDecorator("hg.admin")
def settings_get(self):
return self._settings_get()
@LoginRequired()
@HasPermissionAnyDecorator('hg.admin')
@HasPermissionAnyDecorator("hg.admin")
@CSRFRequired()
def settings_post(self):
return self._settings_post()
@LoginRequired()
@HasPermissionAnyDecorator('hg.admin')
@HasPermissionAnyDecorator("hg.admin")
def new_integration(self):
return self._new_integration()
@ -405,33 +399,32 @@ class RepoIntegrationsView(IntegrationSettingsViewBase):
c.repo_name = self.db_repo.repo_name
c.repository_pull_requests = ScmModel().get_pull_requests(self.repo)
c.repository_artifacts = ScmModel().get_artifacts(self.repo)
c.repository_is_user_following = ScmModel().is_following_repo(
c.repo_name, self._rhodecode_user.user_id)
c.repository_is_user_following = ScmModel().is_following_repo(c.repo_name, self._rhodecode_user.user_id)
c.has_origin_repo_read_perm = False
if self.db_repo.fork:
c.has_origin_repo_read_perm = h.HasRepoPermissionAny(
'repository.write', 'repository.read', 'repository.admin')(
self.db_repo.fork.repo_name, 'summary fork link')
"repository.write", "repository.read", "repository.admin"
)(self.db_repo.fork.repo_name, "summary fork link")
return c
@LoginRequired()
@HasRepoPermissionAnyDecorator('repository.admin')
@HasRepoPermissionAnyDecorator("repository.admin")
def integration_list(self):
return self._integration_list()
@LoginRequired()
@HasRepoPermissionAnyDecorator('repository.admin')
@HasRepoPermissionAnyDecorator("repository.admin")
def settings_get(self):
return self._settings_get()
@LoginRequired()
@HasRepoPermissionAnyDecorator('repository.admin')
@HasRepoPermissionAnyDecorator("repository.admin")
@CSRFRequired()
def settings_post(self):
return self._settings_post()
@LoginRequired()
@HasRepoPermissionAnyDecorator('repository.admin')
@HasRepoPermissionAnyDecorator("repository.admin")
def new_integration(self):
return self._new_integration()
@ -446,22 +439,22 @@ class RepoGroupIntegrationsView(IntegrationSettingsViewBase):
return c
@LoginRequired()
@HasRepoGroupPermissionAnyDecorator('group.admin')
@HasRepoGroupPermissionAnyDecorator("group.admin")
def integration_list(self):
return self._integration_list()
@LoginRequired()
@HasRepoGroupPermissionAnyDecorator('group.admin')
@HasRepoGroupPermissionAnyDecorator("group.admin")
def settings_get(self):
return self._settings_get()
@LoginRequired()
@HasRepoGroupPermissionAnyDecorator('group.admin')
@HasRepoGroupPermissionAnyDecorator("group.admin")
@CSRFRequired()
def settings_post(self):
return self._settings_post()
@LoginRequired()
@HasRepoGroupPermissionAnyDecorator('group.admin')
@HasRepoGroupPermissionAnyDecorator("group.admin")
def new_integration(self):
return self._new_integration()