Changeset - b077cf7e7f90
[Not reviewed]
default
0 6 0
Mads Kiilerich - 6 years ago 2019-07-22 04:18:37
mads@kiilerich.com
helpers: use WebHelpers2 as much as possible - it supports Python3, and WebHelpers is dead

The remaining uses of WebHelpers have to be replaced too - see
https://webhelpers2.readthedocs.io/en/latest/migrate.html .
6 files changed with 34 insertions and 22 deletions:
0 comments (0 inline, 0 general)
kallithea/controllers/search.py
Show inline comments
 
@@ -25,25 +25,25 @@ Original author and date, and relevant c
 
:license: GPLv3, see LICENSE.md for more details.
 
"""
 

	
 
import logging
 
import traceback
 
import urllib
 
from tg.i18n import ugettext as _
 
from tg import request, config, tmpl_context as c
 

	
 
from whoosh.index import open_dir, exists_in, EmptyIndexError
 
from whoosh.qparser import QueryParser, QueryParserError
 
from whoosh.query import Phrase, Prefix
 
from webhelpers.util import update_params
 
from webhelpers2.html.tools import update_params
 

	
 
from kallithea.lib.auth import LoginRequired
 
from kallithea.lib.base import BaseRepoController, render
 
from kallithea.lib.indexers import CHGSETS_SCHEMA, SCHEMA, CHGSET_IDX_NAME, \
 
    IDX_NAME, WhooshResultWrapper
 
from kallithea.lib.page import Page
 
from kallithea.lib.utils2 import safe_str, safe_int
 
from kallithea.model.repo import RepoModel
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
@@ -111,26 +111,25 @@ class SearchController(BaseRepoControlle
 
                    matcher = query.matcher(searcher)
 

	
 
                    log.debug('query: %s', query)
 
                    log.debug('hl terms: %s', highlight_items)
 
                    results = searcher.search(query)
 
                    res_ln = len(results)
 
                    c.runtime = '%s results (%.3f seconds)' % (
 
                        res_ln, results.runtime
 
                    )
 

	
 
                    def url_generator(**kw):
 
                        q = urllib.quote(safe_str(c.cur_query))
 
                        return update_params("?q=%s&type=%s" \
 
                        % (q, safe_str(c.cur_type)), **kw)
 
                        return update_params("?q=%s&type=%s" % (q, safe_str(c.cur_type)), **kw)
 
                    repo_location = RepoModel().repos_path
 
                    c.formated_results = Page(
 
                        WhooshResultWrapper(search_type, searcher, matcher,
 
                                            highlight_items, repo_location),
 
                        page=p,
 
                        item_count=res_ln,
 
                        items_per_page=10,
 
                        url=url_generator
 
                    )
 

	
 
                except QueryParserError:
 
                    c.runtime = _('Invalid search query. Try quoting it.')
kallithea/lib/helpers.py
Show inline comments
 
@@ -22,32 +22,32 @@ import json
 
import StringIO
 
import logging
 
import re
 
import urlparse
 
import textwrap
 
import random
 

	
 
from beaker.cache import cache_region
 
from pygments.formatters.html import HtmlFormatter
 
from pygments import highlight as code_highlight
 
from tg.i18n import ugettext as _
 

	
 
from webhelpers.html import literal, HTML, escape
 
from webhelpers.html.tags import checkbox, end_form, hidden, link_to, \
 
    select, submit, text, password, textarea, radio, form as insecure_form
 
from webhelpers.number import format_byte_size
 
from webhelpers2.html import literal, HTML, escape
 
from webhelpers2.html.tags import checkbox, end_form, hidden, link_to, \
 
    select as webhelpers2_select, Option, Options, \
 
    submit, text, password, textarea, radio, form as insecure_form
 
from webhelpers2.number import format_byte_size
 
from webhelpers.pylonslib import Flash as _Flash
 
from webhelpers.text import chop_at, truncate, wrap_paragraphs
 
from webhelpers.html.tags import _set_input_attrs, _set_id_attr, \
 
    convert_boolean_attrs, NotGiven, _make_safe_id_component
 
from webhelpers2.text import chop_at, truncate, wrap_paragraphs
 
from webhelpers2.html.tags import _input, NotGiven, _make_safe_id_component
 

	
 
from kallithea.config.routing import url
 
from kallithea.lib.annotate import annotate_highlight
 
from kallithea.lib.pygmentsutils import get_custom_lexer
 
from kallithea.lib.utils2 import str2bool, safe_unicode, safe_str, \
 
    time_to_datetime, AttributeDict, safe_int, MENTIONS_REGEX
 
from kallithea.lib.markup_renderer import url_re
 
from kallithea.lib.vcs.exceptions import ChangesetDoesNotExistError
 
from kallithea.lib.vcs.backends.base import BaseChangeset, EmptyChangeset
 

	
 
log = logging.getLogger(__name__)
 

	
 
@@ -135,35 +135,47 @@ def jshtml(val):
 

	
 
def shorter(s, size=20, firstline=False, postfix='...'):
 
    """Truncate s to size, including the postfix string if truncating.
 
    If firstline, truncate at newline.
 
    """
 
    if firstline:
 
        s = s.split('\n', 1)[0].rstrip()
 
    if len(s) > size:
 
        return s[:size - len(postfix)] + postfix
 
    return s
 

	
 

	
 
def _reset(name, value=None, id=NotGiven, type="reset", **attrs):
 
    """
 
    Reset button
 
    """
 
    _set_input_attrs(attrs, type, name, value)
 
    _set_id_attr(attrs, id, name)
 
    convert_boolean_attrs(attrs, ["disabled"])
 
    return HTML.input(**attrs)
 
def reset(name, value, id=NotGiven, **attrs):
 
    """Create a reset button, similar to webhelpers2.html.tags.submit ."""
 
    return _input("reset", name, value, id, attrs)
 

	
 

	
 
reset = _reset
 
def select(name, selected_values, options, id=NotGiven, **attrs):
 
    """Convenient wrapper of webhelpers2 to let it accept options as a tuple list"""
 
    if isinstance(options, list):
 
        l = []
 
        for x in options:
 
            try:
 
                value, label = x
 
            except ValueError: # too many values to unpack
 
                if isinstance(x, basestring):
 
                    value = label = x
 
                else:
 
                    log.error('invalid select option %r', x)
 
                    raise
 
            l.append(Option(label, value))
 
        options = Options(l)
 
    return webhelpers2_select(name, selected_values, options, id=id, **attrs)
 

	
 

	
 
safeid = _make_safe_id_component
 

	
 

	
 
def FID(raw_id, path):
 
    """
 
    Creates a unique ID for filenode based on it's hash of path and revision
 
    it's safe to use in urls
 

	
 
    :param raw_id:
 
    :param path:
 
    """
 

	
kallithea/lib/page.py
Show inline comments
 
@@ -9,25 +9,25 @@
 
# 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/>.
 
"""
 
Custom paging classes
 
"""
 
import logging
 
import math
 
import re
 
from kallithea.config.routing import url
 
from webhelpers.html import literal, HTML
 
from webhelpers2.html import literal, HTML
 
from webhelpers.paginate import Page as _Page
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class Page(_Page):
 
    """
 
    Custom pager emitting Bootstrap paginators
 
    """
 

	
 
    def __init__(self, *args, **kwargs):
 
        kwargs.setdefault('url', url.current)
kallithea/lib/utils2.py
Show inline comments
 
@@ -31,25 +31,25 @@ Original author and date, and relevant c
 
import os
 
import re
 
import sys
 
import time
 
import uuid
 
import datetime
 
import urllib
 
import binascii
 
import pwd
 

	
 
import webob
 
import urlobject
 
from webhelpers.text import collapse, remove_formatting, strip_tags
 
from webhelpers2.text import collapse, remove_formatting, strip_tags
 

	
 
from tg.i18n import ugettext as _, ungettext
 
from kallithea.lib.vcs.utils.lazy import LazyProperty
 
from kallithea.lib.compat import json
 

	
 

	
 
def str2bool(_str):
 
    """
 
    returns True/False value from given string, it tries to translate the
 
    string into boolean
 

	
 
    :param _str: string value to translate into boolean
kallithea/model/db.py
Show inline comments
 
@@ -1486,25 +1486,25 @@ class RepoGroup(Base, BaseDbModel):
 

	
 
    def __init__(self, group_name='', parent_group=None):
 
        self.group_name = group_name
 
        self.parent_group = parent_group
 

	
 
    def __unicode__(self):
 
        return u"<%s('id:%s:%s')>" % (self.__class__.__name__, self.group_id,
 
                                      self.group_name)
 

	
 
    @classmethod
 
    def _generate_choice(cls, repo_group):
 
        """Return tuple with group_id and name as html literal"""
 
        from webhelpers.html import literal
 
        from webhelpers2.html import literal
 
        if repo_group is None:
 
            return (-1, u'-- %s --' % _('top level'))
 
        return repo_group.group_id, literal(cls.SEP.join(repo_group.full_path_splitted))
 

	
 
    @classmethod
 
    def groups_choices(cls, groups):
 
        """Return tuples with group_id and name as html literal."""
 
        return sorted((cls._generate_choice(g) for g in groups),
 
                      key=lambda c: c[1].split(cls.SEP))
 

	
 
    @classmethod
 
    def url_sep(cls):
setup.py
Show inline comments
 
@@ -35,24 +35,25 @@ __platform__ = platform.system()
 
is_windows = __platform__ in ['Windows']
 

	
 
requirements = [
 
    "alembic >= 0.8.0, < 1.1",
 
    "gearbox < 1",
 
    "waitress >= 0.8.8, < 1.4",
 
    "WebOb >= 1.7, < 1.8", # turbogears2 2.3.12 requires WebOb<1.8.0
 
    "backlash >= 0.1.2, < 1",
 
    "TurboGears2 >= 2.3.10, < 2.4", # TODO: 2.4 drops Pylons compatibility
 
    "tgext.routes >= 0.2.0, < 1",
 
    "Beaker >= 1.7.0, < 2",
 
    "WebHelpers >= 1.3, < 1.4",
 
    "WebHelpers2 >= 2.0, < 2.1",
 
    "FormEncode >= 1.3.0, < 1.4",
 
    "SQLAlchemy >= 1.1, < 1.4",
 
    "Mako >= 0.9.0, < 1.1",
 
    "Pygments >= 2.0, < 2.5",
 
    "Whoosh >= 2.5.0, < 2.8",
 
    "celery >= 3.1, < 4.0", # TODO: celery 4 doesn't work
 
    "Babel >= 1.3, < 2.8",
 
    "python-dateutil >= 1.5.0, < 2.9",
 
    "Markdown >= 2.2.1, < 3.2",
 
    "docutils >= 0.11, < 0.15",
 
    "URLObject >= 2.3.4, < 2.5",
 
    "Routes >= 1.13, < 2", # TODO: bumping to 2.0 will make test_file_annotation fail
0 comments (0 inline, 0 general)