changeset 8679:0be48652ca48

routing: separate url handling from routing - move it to webutils This is a helper method relying on the thread local tg.request. We didn't have a good place to put it. Now we do. This (re)moves unfortunate dependencies to the routing module (which almost is a controller).
author Mads Kiilerich <mads@kiilerich.com>
date Sat, 10 Oct 2020 22:13:50 +0200
parents 16a359ce1801
children bc1fff7ae770
files kallithea/config/routing.py kallithea/controllers/admin/auth_settings.py kallithea/controllers/admin/defaults.py kallithea/controllers/admin/gists.py kallithea/controllers/admin/my_account.py kallithea/controllers/admin/permissions.py kallithea/controllers/admin/repo_groups.py kallithea/controllers/admin/repos.py kallithea/controllers/admin/settings.py kallithea/controllers/admin/user_groups.py kallithea/controllers/admin/users.py kallithea/controllers/changelog.py kallithea/controllers/compare.py kallithea/controllers/files.py kallithea/controllers/forks.py kallithea/controllers/login.py kallithea/controllers/pullrequests.py kallithea/lib/auth.py kallithea/lib/base.py kallithea/lib/helpers.py kallithea/lib/page.py kallithea/lib/webutils.py kallithea/tests/other/test_libs.py
diffstat 23 files changed, 74 insertions(+), 52 deletions(-) [+]
line wrap: on
line diff
--- a/kallithea/config/routing.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/config/routing.py	Sat Oct 10 22:13:50 2020 +0200
@@ -20,7 +20,6 @@
 """
 
 import routes
-from tg import request
 
 from kallithea.lib.utils2 import safe_str
 
@@ -775,29 +774,3 @@
                  conditions=dict(function=check_repo))
 
     return rmap
-
-
-class UrlGenerator(object):
-    """Emulate pylons.url in providing a wrapper around routes.url
-
-    This code was added during migration from Pylons to Turbogears2. Pylons
-    already provided a wrapper like this, but Turbogears2 does not.
-
-    When the routing of Kallithea is changed to use less Routes and more
-    Turbogears2-style routing, this class may disappear or change.
-
-    url() (the __call__ method) returns the URL based on a route name and
-    arguments.
-    url.current() returns the URL of the current page with arguments applied.
-
-    Refer to documentation of Routes for details:
-    https://routes.readthedocs.io/en/latest/generating.html#generation
-    """
-    def __call__(self, *args, **kwargs):
-        return request.environ['routes.url'](*args, **kwargs)
-
-    def current(self, *args, **kwargs):
-        return request.environ['routes.url'].current(*args, **kwargs)
-
-
-url = UrlGenerator()
--- a/kallithea/controllers/admin/auth_settings.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/controllers/admin/auth_settings.py	Sat Oct 10 22:13:50 2020 +0200
@@ -32,11 +32,11 @@
 from tg.i18n import ugettext as _
 from webob.exc import HTTPFound
 
-from kallithea.config.routing import url
 from kallithea.lib import auth_modules
 from kallithea.lib import helpers as h
 from kallithea.lib.auth import HasPermissionAnyDecorator, LoginRequired
 from kallithea.lib.base import BaseController, render
+from kallithea.lib.webutils import url
 from kallithea.model.db import Setting
 from kallithea.model.forms import AuthSettingsForm
 from kallithea.model.meta import Session
--- a/kallithea/controllers/admin/defaults.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/controllers/admin/defaults.py	Sat Oct 10 22:13:50 2020 +0200
@@ -34,10 +34,10 @@
 from tg.i18n import ugettext as _
 from webob.exc import HTTPFound
 
-from kallithea.config.routing import url
 from kallithea.lib import helpers as h
 from kallithea.lib.auth import HasPermissionAnyDecorator, LoginRequired
 from kallithea.lib.base import BaseController, render
+from kallithea.lib.webutils import url
 from kallithea.model.db import Setting
 from kallithea.model.forms import DefaultsForm
 from kallithea.model.meta import Session
--- a/kallithea/controllers/admin/gists.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/controllers/admin/gists.py	Sat Oct 10 22:13:50 2020 +0200
@@ -35,13 +35,13 @@
 from tg.i18n import ugettext as _
 from webob.exc import HTTPForbidden, HTTPFound, HTTPNotFound
 
-from kallithea.config.routing import url
 from kallithea.lib import helpers as h
 from kallithea.lib.auth import LoginRequired
 from kallithea.lib.base import BaseController, jsonify, render
 from kallithea.lib.page import Page
 from kallithea.lib.utils2 import safe_int, safe_str, time_to_datetime
 from kallithea.lib.vcs.exceptions import NodeNotChangedError, VCSError
+from kallithea.lib.webutils import url
 from kallithea.model.db import Gist
 from kallithea.model.forms import GistForm
 from kallithea.model.gist import GistModel
--- a/kallithea/controllers/admin/my_account.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/controllers/admin/my_account.py	Sat Oct 10 22:13:50 2020 +0200
@@ -35,12 +35,12 @@
 from tg.i18n import ugettext as _
 from webob.exc import HTTPFound
 
-from kallithea.config.routing import url
 from kallithea.lib import auth_modules
 from kallithea.lib import helpers as h
 from kallithea.lib.auth import AuthUser, LoginRequired
 from kallithea.lib.base import BaseController, IfSshEnabled, render
 from kallithea.lib.utils2 import generate_api_key, safe_int
+from kallithea.lib.webutils import url
 from kallithea.model.api_key import ApiKeyModel
 from kallithea.model.db import Repository, User, UserEmailMap, UserFollowing
 from kallithea.model.forms import PasswordChangeForm, UserForm
--- a/kallithea/controllers/admin/permissions.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/controllers/admin/permissions.py	Sat Oct 10 22:13:50 2020 +0200
@@ -36,10 +36,10 @@
 from tg.i18n import ugettext as _
 from webob.exc import HTTPFound
 
-from kallithea.config.routing import url
 from kallithea.lib import helpers as h
 from kallithea.lib.auth import AuthUser, HasPermissionAnyDecorator, LoginRequired
 from kallithea.lib.base import BaseController, render
+from kallithea.lib.webutils import url
 from kallithea.model.db import User, UserIpMap
 from kallithea.model.forms import DefaultPermissionsForm
 from kallithea.model.meta import Session
--- a/kallithea/controllers/admin/repo_groups.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/controllers/admin/repo_groups.py	Sat Oct 10 22:13:50 2020 +0200
@@ -36,11 +36,11 @@
 from tg.i18n import ungettext
 from webob.exc import HTTPForbidden, HTTPFound, HTTPInternalServerError, HTTPNotFound
 
-from kallithea.config.routing import url
 from kallithea.lib import helpers as h
 from kallithea.lib.auth import HasPermissionAny, HasRepoGroupPermissionLevel, HasRepoGroupPermissionLevelDecorator, LoginRequired
 from kallithea.lib.base import BaseController, render
 from kallithea.lib.utils2 import safe_int
+from kallithea.lib.webutils import url
 from kallithea.model.db import RepoGroup, Repository
 from kallithea.model.forms import RepoGroupForm, RepoGroupPermsForm
 from kallithea.model.meta import Session
--- a/kallithea/controllers/admin/repos.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/controllers/admin/repos.py	Sat Oct 10 22:13:50 2020 +0200
@@ -37,7 +37,6 @@
 from webob.exc import HTTPForbidden, HTTPFound, HTTPInternalServerError, HTTPNotFound
 
 import kallithea
-from kallithea.config.routing import url
 from kallithea.lib import helpers as h
 from kallithea.lib.auth import HasRepoPermissionLevelDecorator, LoginRequired, NotAnonymous
 from kallithea.lib.base import BaseRepoController, jsonify, render
@@ -45,6 +44,7 @@
 from kallithea.lib.utils import action_logger
 from kallithea.lib.utils2 import safe_int
 from kallithea.lib.vcs import RepositoryError
+from kallithea.lib.webutils import url
 from kallithea.model.db import RepoGroup, Repository, RepositoryField, Setting, UserFollowing
 from kallithea.model.forms import RepoFieldForm, RepoForm, RepoPermsForm
 from kallithea.model.meta import Session
--- a/kallithea/controllers/admin/settings.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/controllers/admin/settings.py	Sat Oct 10 22:13:50 2020 +0200
@@ -35,7 +35,6 @@
 from tg.i18n import ugettext as _
 from webob.exc import HTTPFound
 
-from kallithea.config.routing import url
 from kallithea.lib import helpers as h
 from kallithea.lib.auth import HasPermissionAnyDecorator, LoginRequired
 from kallithea.lib.base import BaseController, render
@@ -43,6 +42,7 @@
 from kallithea.lib.utils import repo2db_mapper, set_app_settings
 from kallithea.lib.utils2 import safe_str
 from kallithea.lib.vcs import VCSError
+from kallithea.lib.webutils import url
 from kallithea.model.db import Repository, Setting, Ui
 from kallithea.model.forms import ApplicationSettingsForm, ApplicationUiSettingsForm, ApplicationVisualisationForm
 from kallithea.model.meta import Session
--- a/kallithea/controllers/admin/user_groups.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/controllers/admin/user_groups.py	Sat Oct 10 22:13:50 2020 +0200
@@ -37,13 +37,13 @@
 from tg.i18n import ugettext as _
 from webob.exc import HTTPFound, HTTPInternalServerError
 
-from kallithea.config.routing import url
 from kallithea.lib import helpers as h
 from kallithea.lib.auth import HasPermissionAnyDecorator, HasUserGroupPermissionLevelDecorator, LoginRequired
 from kallithea.lib.base import BaseController, render
 from kallithea.lib.exceptions import RepoGroupAssignmentError, UserGroupsAssignedException
 from kallithea.lib.utils import action_logger
 from kallithea.lib.utils2 import safe_int, safe_str
+from kallithea.lib.webutils import url
 from kallithea.model.db import User, UserGroup, UserGroupRepoGroupToPerm, UserGroupRepoToPerm, UserGroupToPerm
 from kallithea.model.forms import CustomDefaultPermissionsForm, UserGroupForm, UserGroupPermsForm
 from kallithea.model.meta import Session
--- a/kallithea/controllers/admin/users.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/controllers/admin/users.py	Sat Oct 10 22:13:50 2020 +0200
@@ -37,7 +37,6 @@
 from webob.exc import HTTPFound, HTTPNotFound
 
 import kallithea
-from kallithea.config.routing import url
 from kallithea.lib import auth_modules
 from kallithea.lib import helpers as h
 from kallithea.lib.auth import AuthUser, HasPermissionAnyDecorator, LoginRequired
@@ -45,6 +44,7 @@
 from kallithea.lib.exceptions import DefaultUserException, UserCreationError, UserOwnsReposException
 from kallithea.lib.utils import action_logger
 from kallithea.lib.utils2 import datetime_to_time, generate_api_key, safe_int
+from kallithea.lib.webutils import url
 from kallithea.model.api_key import ApiKeyModel
 from kallithea.model.db import User, UserEmailMap, UserIpMap, UserToPerm
 from kallithea.model.forms import CustomDefaultPermissionsForm, UserForm
--- a/kallithea/controllers/changelog.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/controllers/changelog.py	Sat Oct 10 22:13:50 2020 +0200
@@ -34,13 +34,13 @@
 from webob.exc import HTTPBadRequest, HTTPFound, HTTPNotFound
 
 import kallithea.lib.helpers as h
-from kallithea.config.routing import url
 from kallithea.lib.auth import HasRepoPermissionLevelDecorator, LoginRequired
 from kallithea.lib.base import BaseRepoController, render
 from kallithea.lib.graphmod import graph_data
 from kallithea.lib.page import Page
 from kallithea.lib.utils2 import safe_int
 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, ChangesetError, EmptyRepositoryError, NodeDoesNotExistError, RepositoryError
+from kallithea.lib.webutils import url
 
 
 log = logging.getLogger(__name__)
--- a/kallithea/controllers/compare.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/controllers/compare.py	Sat Oct 10 22:13:50 2020 +0200
@@ -34,12 +34,12 @@
 from tg.i18n import ugettext as _
 from webob.exc import HTTPBadRequest, HTTPFound, HTTPNotFound
 
-from kallithea.config.routing import url
 from kallithea.lib import diffs
 from kallithea.lib import helpers as h
 from kallithea.lib.auth import HasRepoPermissionLevelDecorator, LoginRequired
 from kallithea.lib.base import BaseRepoController, render
 from kallithea.lib.graphmod import graph_data
+from kallithea.lib.webutils import url
 from kallithea.model.db import Repository
 
 
--- a/kallithea/controllers/files.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/controllers/files.py	Sat Oct 10 22:13:50 2020 +0200
@@ -39,7 +39,6 @@
 from webob.exc import HTTPFound, HTTPNotFound
 
 import kallithea
-from kallithea.config.routing import url
 from kallithea.lib import diffs
 from kallithea.lib import helpers as h
 from kallithea.lib.auth import HasRepoPermissionLevelDecorator, LoginRequired
@@ -52,6 +51,7 @@
 from kallithea.lib.vcs.exceptions import (ChangesetDoesNotExistError, ChangesetError, EmptyRepositoryError, ImproperArchiveTypeError, NodeAlreadyExistsError,
                                           NodeDoesNotExistError, NodeError, RepositoryError, VCSError)
 from kallithea.lib.vcs.nodes import FileNode
+from kallithea.lib.webutils import url
 from kallithea.model.repo import RepoModel
 from kallithea.model.scm import ScmModel
 
--- a/kallithea/controllers/forks.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/controllers/forks.py	Sat Oct 10 22:13:50 2020 +0200
@@ -37,11 +37,11 @@
 
 import kallithea
 import kallithea.lib.helpers as h
-from kallithea.config.routing import url
 from kallithea.lib.auth import HasPermissionAnyDecorator, HasRepoPermissionLevel, HasRepoPermissionLevelDecorator, LoginRequired
 from kallithea.lib.base import BaseRepoController, render
 from kallithea.lib.page import Page
 from kallithea.lib.utils2 import safe_int
+from kallithea.lib.webutils import url
 from kallithea.model.db import Repository, Ui, UserFollowing
 from kallithea.model.forms import RepoForkForm
 from kallithea.model.repo import RepoModel
--- a/kallithea/controllers/login.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/controllers/login.py	Sat Oct 10 22:13:50 2020 +0200
@@ -37,10 +37,10 @@
 from webob.exc import HTTPBadRequest, HTTPFound
 
 import kallithea.lib.helpers as h
-from kallithea.config.routing import url
 from kallithea.lib.auth import AuthUser, HasPermissionAnyDecorator
 from kallithea.lib.base import BaseController, log_in_user, render
 from kallithea.lib.exceptions import UserCreationError
+from kallithea.lib.webutils import url
 from kallithea.model.db import Setting, User
 from kallithea.model.forms import LoginForm, PasswordResetConfirmationForm, PasswordResetRequestForm, RegisterForm
 from kallithea.model.meta import Session
--- a/kallithea/controllers/pullrequests.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/controllers/pullrequests.py	Sat Oct 10 22:13:50 2020 +0200
@@ -35,7 +35,6 @@
 from tg.i18n import ugettext as _
 from webob.exc import HTTPBadRequest, HTTPForbidden, HTTPFound, HTTPNotFound
 
-from kallithea.config.routing import url
 from kallithea.controllers.changeset import create_cs_pr_comment, delete_cs_pr_comment
 from kallithea.lib import diffs
 from kallithea.lib import helpers as h
@@ -45,6 +44,7 @@
 from kallithea.lib.page import Page
 from kallithea.lib.utils2 import ascii_bytes, safe_bytes, safe_int
 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, EmptyRepositoryError
+from kallithea.lib.webutils import url
 from kallithea.model.changeset_status import ChangesetStatusModel
 from kallithea.model.comment import ChangesetCommentsModel
 from kallithea.model.db import ChangesetStatus, PullRequest, PullRequestReviewer, Repository, User
--- a/kallithea/lib/auth.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/lib/auth.py	Sat Oct 10 22:13:50 2020 +0200
@@ -40,10 +40,10 @@
 from webob.exc import HTTPForbidden, HTTPFound
 
 import kallithea
-from kallithea.config.routing import url
 from kallithea.lib.utils import get_repo_group_slug, get_repo_slug, get_user_group_slug
 from kallithea.lib.utils2 import ascii_bytes, ascii_str, safe_bytes
 from kallithea.lib.vcs.utils.lazy import LazyProperty
+from kallithea.lib.webutils import url
 from kallithea.model.db import (Permission, UserApiKeys, UserGroup, UserGroupMember, UserGroupRepoGroupToPerm, UserGroupRepoToPerm, UserGroupToPerm,
                                 UserGroupUserGroupToPerm, UserIpMap, UserToPerm)
 from kallithea.model.meta import Session
--- a/kallithea/lib/base.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/lib/base.py	Sat Oct 10 22:13:50 2020 +0200
@@ -44,13 +44,13 @@
 from tg.i18n import ugettext as _
 
 import kallithea
-from kallithea.config.routing import url
 from kallithea.lib import auth_modules, ext_json
 from kallithea.lib.auth import AuthUser, HasPermissionAnyMiddleware
 from kallithea.lib.exceptions import UserCreationError
 from kallithea.lib.utils import get_repo_slug, is_valid_repo
 from kallithea.lib.utils2 import AttributeDict, asbool, ascii_bytes, safe_int, safe_str, set_hook_environment
 from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError, EmptyRepositoryError, RepositoryError
+from kallithea.lib.webutils import url
 from kallithea.model import meta
 from kallithea.model.db import PullRequest, Repository, Setting, User
 from kallithea.model.scm import ScmModel
--- a/kallithea/lib/helpers.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/lib/helpers.py	Sat Oct 10 22:13:50 2020 +0200
@@ -40,7 +40,6 @@
 from webhelpers2.text import chop_at, truncate, wrap_paragraphs
 
 import kallithea
-from kallithea.config.routing import url
 from kallithea.lib.annotate import annotate_highlight
 #==============================================================================
 # PERMS
@@ -56,6 +55,7 @@
 # SCM FILTERS available via h.
 #==============================================================================
 from kallithea.lib.vcs.utils import author_email, author_name
+from kallithea.lib.webutils import url
 from kallithea.model.changeset_status import ChangesetStatusModel
 from kallithea.model.db import ChangesetStatus, Permission, PullRequest, User, UserIpMap
 
--- a/kallithea/lib/page.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/lib/page.py	Sat Oct 10 22:13:50 2020 +0200
@@ -21,7 +21,7 @@
 import sqlalchemy.orm
 from webhelpers2.html import literal
 
-from kallithea.config.routing import url
+from kallithea.lib.webutils import url
 
 
 log = logging.getLogger(__name__)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/kallithea/lib/webutils.py	Sat Oct 10 22:13:50 2020 +0200
@@ -0,0 +1,49 @@
+# -*- coding: utf-8 -*-
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+"""
+kallithea.lib.webutils
+~~~~~~~~~~~~~~~~~~~~
+
+Helper functions that rely on the current WSGI request, exposed in the TG2
+thread-local "global" variables. It should have few dependencies so it can be
+imported anywhere - just like the global variables can be used everywhere.
+"""
+
+from tg import request
+
+
+class UrlGenerator(object):
+    """Emulate pylons.url in providing a wrapper around routes.url
+
+    This code was added during migration from Pylons to Turbogears2. Pylons
+    already provided a wrapper like this, but Turbogears2 does not.
+
+    When the routing of Kallithea is changed to use less Routes and more
+    Turbogears2-style routing, this class may disappear or change.
+
+    url() (the __call__ method) returns the URL based on a route name and
+    arguments.
+    url.current() returns the URL of the current page with arguments applied.
+
+    Refer to documentation of Routes for details:
+    https://routes.readthedocs.io/en/latest/generating.html#generation
+    """
+    def __call__(self, *args, **kwargs):
+        return request.environ['routes.url'](*args, **kwargs)
+
+    def current(self, *args, **kwargs):
+        return request.environ['routes.url'].current(*args, **kwargs)
+
+
+url = UrlGenerator()
--- a/kallithea/tests/other/test_libs.py	Sun Oct 11 11:52:22 2020 +0200
+++ b/kallithea/tests/other/test_libs.py	Sat Oct 10 22:13:50 2020 +0200
@@ -219,10 +219,10 @@
 
             return _c
 
-        with mock.patch('kallithea.config.routing.url.current', lambda *a, **b: 'https://example.com'):
+        with mock.patch('kallithea.lib.webutils.url.current', lambda *a, **b: 'https://example.com'):
             fake = fake_tmpl_context(_url='http://example.com/{email}')
             with mock.patch('tg.tmpl_context', fake):
-                    from kallithea.config.routing import url
+                    from kallithea.lib.webutils import url
                     assert url.current() == 'https://example.com'
                     grav = gravatar_url(email_address='test@example.com', size=24)
                     assert grav == 'http://example.com/test@example.com'
@@ -318,7 +318,7 @@
     def test_urlify_text(self, sample, expected):
         expected = self._quick_url(expected)
 
-        with mock.patch('kallithea.config.routing.UrlGenerator.__call__',
+        with mock.patch('kallithea.lib.webutils.UrlGenerator.__call__',
             lambda self, name, **kwargs: dict(changeset_home='/%(repo_name)s/changeset/%(revision)s')[name] % kwargs,
         ):
             from kallithea.lib.helpers import urlify_text
@@ -374,7 +374,7 @@
     def test_urlify_test(self, sample, expected, url_):
         expected = self._quick_url(expected,
                                    tmpl="""<a href="%s">%s</a>""", url_=url_)
-        with mock.patch('kallithea.config.routing.UrlGenerator.__call__',
+        with mock.patch('kallithea.lib.webutils.UrlGenerator.__call__',
             lambda self, name, **kwargs: dict(changeset_home='/%(repo_name)s/changeset/%(revision)s')[name] % kwargs,
         ):
             from kallithea.lib.helpers import urlify_text
@@ -388,7 +388,7 @@
        """<a class="message-link" href="#the-link"> yo</a>"""),
     ])
     def test_urlify_link(self, sample, expected):
-        with mock.patch('kallithea.config.routing.UrlGenerator.__call__',
+        with mock.patch('kallithea.lib.webutils.UrlGenerator.__call__',
             lambda self, name, **kwargs: dict(changeset_home='/%(repo_name)s/changeset/%(revision)s')[name] % kwargs,
         ):
             from kallithea.lib.helpers import urlify_text