Changeset - 7691290837d2
[Not reviewed]
default
! ! !
Lars Kruse - 8 years ago 2017-08-25 14:32:50
devel@sumpfralle.de
codingstyle: trivial whitespace fixes

Reported by flake8.
90 files changed with 175 insertions and 77 deletions:
0 comments (0 inline, 0 general)
kallithea/bin/kallithea_api.py
Show inline comments
 
@@ -121,5 +121,6 @@ def main(argv=None):
 
        )
 
    return 0
 

	
 

	
 
if __name__ == '__main__':
 
    sys.exit(main(sys.argv))
kallithea/bin/kallithea_backup.py
Show inline comments
 
@@ -92,6 +92,7 @@ class BackupManager(object):
 
        logging.info('Removing file %s', self.backup_file_name)
 
        os.remove(os.path.join(self.backup_file_path, self.backup_file_name))
 

	
 

	
 
if __name__ == "__main__":
 

	
 
    repo_location = '/home/repo_path'
kallithea/config/app_cfg.py
Show inline comments
 
@@ -95,6 +95,7 @@ class KallitheaAppConfig(AppConfig):
 
        # Disable transaction manager -- currently Kallithea takes care of transactions itself
 
        self['tm.enabled'] = False
 

	
 

	
 
base_config = KallitheaAppConfig()
 

	
 
# TODO still needed as long as we use pylonslib
 
@@ -174,6 +175,7 @@ def setup_configuration(app):
 
        repo2db_mapper(ScmModel().repo_scan(repos_path),
 
                       remove_obsolete=False, install_git_hooks=False)
 

	
 

	
 
hooks.register('configure_new_app', setup_configuration)
 

	
 

	
 
@@ -190,4 +192,5 @@ def setup_application(app):
 
        app = HttpsFixup(app, config)
 
    return app
 

	
 

	
 
hooks.register('before_config', setup_application)
kallithea/config/middleware.py
Show inline comments
 
@@ -23,10 +23,12 @@ __all__ = ['make_app']
 
# make_base_app will wrap the TurboGears2 app with all the middleware it needs.
 
make_base_app = base_config.setup_tg_wsgi_app(load_environment)
 

	
 

	
 
def make_app_without_logging(global_conf, full_stack=True, **app_conf):
 
    """The core of make_app for use from gearbox commands (other than 'serve')"""
 
    return make_base_app(global_conf, full_stack=full_stack, **app_conf)
 

	
 

	
 
def make_app(global_conf, full_stack=True, **app_conf):
 
    """
 
    Set up Kallithea with the settings found in the PasteDeploy configuration
kallithea/config/post_receive_tmpl.py
Show inline comments
 
@@ -25,5 +25,6 @@ def main():
 
    _handler(repo_path, push_data, os.environ)
 
    sys.exit(0)
 

	
 

	
 
if __name__ == '__main__':
 
    main()
kallithea/config/pre_receive_tmpl.py
Show inline comments
 
@@ -25,5 +25,6 @@ def main():
 
    _handler(repo_path, push_data, os.environ)
 
    sys.exit(0)
 

	
 

	
 
if __name__ == '__main__':
 
    main()
kallithea/config/rcextensions/__init__.py
Show inline comments
 
@@ -49,6 +49,8 @@ def _crrepohook(*args, **kwargs):
 
     :param created_by:
 
    """
 
    return 0
 

	
 

	
 
CREATE_REPO_HOOK = _crrepohook
 

	
 

	
 
@@ -73,6 +75,8 @@ def _pre_cruserhook(*args, **kwargs):
 
    """
 
    reason = 'allowed'
 
    return True, reason
 

	
 

	
 
PRE_CREATE_USER_HOOK = _pre_cruserhook
 

	
 
#==============================================================================
 
@@ -105,6 +109,8 @@ def _cruserhook(*args, **kwargs):
 
      :param created_by:
 
    """
 
    return 0
 

	
 

	
 
CREATE_USER_HOOK = _cruserhook
 

	
 

	
 
@@ -132,6 +138,8 @@ def _dlrepohook(*args, **kwargs):
 
     :param deleted_on:
 
    """
 
    return 0
 

	
 

	
 
DELETE_REPO_HOOK = _dlrepohook
 

	
 

	
 
@@ -165,6 +173,8 @@ def _dluserhook(*args, **kwargs):
 
      :param deleted_by:
 
    """
 
    return 0
 

	
 

	
 
DELETE_USER_HOOK = _dluserhook
 

	
 

	
 
@@ -189,6 +199,8 @@ def _pushhook(*args, **kwargs):
 
      :param pushed_revs: list of pushed revisions
 
    """
 
    return 0
 

	
 

	
 
PUSH_HOOK = _pushhook
 

	
 

	
 
@@ -212,4 +224,6 @@ def _pullhook(*args, **kwargs):
 
      :param repository: repository name
 
    """
 
    return 0
 

	
 

	
 
PULL_HOOK = _pullhook
kallithea/config/routing.py
Show inline comments
 
@@ -161,7 +161,6 @@ def make_map(config):
 
                  action="delete", conditions=dict(method=["POST"],
 
                                                   function=check_group_skip_path))
 

	
 

	
 
    #ADMIN USER ROUTES
 
    with rmap.submapper(path_prefix=ADMIN_PREFIX,
 
                        controller='admin/users') as m:
 
@@ -233,7 +232,6 @@ def make_map(config):
 
        m.connect("edit_user_group_default_perms_update", "/user_groups/{id}/edit/default_perms",
 
                  action="update_default_perms", conditions=dict(method=["POST"]))
 

	
 

	
 
        m.connect("edit_user_group_perms", "/user_groups/{id}/edit/perms",
 
                  action="edit_perms", conditions=dict(method=["GET"]))
 
        m.connect("edit_user_group_perms_update", "/user_groups/{id}/edit/perms",
 
@@ -247,8 +245,6 @@ def make_map(config):
 
        m.connect("edit_user_group_members", "/user_groups/{id}/edit/members",
 
                  action="edit_members", conditions=dict(method=["GET"]))
 

	
 

	
 

	
 
    #ADMIN PERMISSIONS ROUTES
 
    with rmap.submapper(path_prefix=ADMIN_PREFIX,
 
                        controller='admin/permissions') as m:
 
@@ -263,7 +259,6 @@ def make_map(config):
 
        m.connect("admin_permissions_perms", "/permissions/perms",
 
                  action="permission_perms", conditions=dict(method=["GET"]))
 

	
 

	
 
    #ADMIN DEFAULTS ROUTES
 
    with rmap.submapper(path_prefix=ADMIN_PREFIX,
 
                        controller='admin/defaults') as m:
 
@@ -391,7 +386,6 @@ def make_map(config):
 
        m.connect("new_gist", "/gists/new",
 
                  action="new", conditions=dict(method=["GET"]))
 

	
 

	
 
        m.connect("gist_delete", "/gists/{gist_id}/delete",
 
                  action="delete", conditions=dict(method=["POST"]))
 
        m.connect("edit_gist", "/gists/{gist_id}/edit",
 
@@ -399,7 +393,6 @@ def make_map(config):
 
        m.connect("edit_gist_check_revision", "/gists/{gist_id}/edit/check_revision",
 
                  action="check_revision", conditions=dict(method=["POST"]))
 

	
 

	
 
        m.connect("gist", "/gists/{gist_id}",
 
                  action="show", conditions=dict(method=["GET"]))
 
        m.connect("gist_rev", "/gists/{gist_id}/{revision}",
 
@@ -551,7 +544,6 @@ def make_map(config):
 
                 controller='admin/repos', action="delete_repo_field",
 
                 conditions=dict(method=["POST"], function=check_repo))
 

	
 

	
 
    rmap.connect("edit_repo_advanced", "/{repo_name:.*?}/settings/advanced",
 
                 controller='admin/repos', action="edit_advanced",
 
                 conditions=dict(method=["GET"], function=check_repo))
 
@@ -571,7 +563,6 @@ def make_map(config):
 
                 controller='admin/repos', action="edit_advanced_fork",
 
                 conditions=dict(method=["POST"], function=check_repo))
 

	
 

	
 
    rmap.connect("edit_repo_caches", "/{repo_name:.*?}/settings/caches",
 
                 controller='admin/repos', action="edit_caches",
 
                 conditions=dict(method=["GET"], function=check_repo))
 
@@ -579,7 +570,6 @@ def make_map(config):
 
                 controller='admin/repos', action="edit_caches",
 
                 conditions=dict(method=["POST"], function=check_repo))
 

	
 

	
 
    rmap.connect("edit_repo_remote", "/{repo_name:.*?}/settings/remote",
 
                 controller='admin/repos', action="edit_remote",
 
                 conditions=dict(method=["GET"], function=check_repo))
 
@@ -812,7 +802,9 @@ class UrlGenerator(object):
 
    """
 
    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()
kallithea/controllers/admin/gists.py
Show inline comments
 
@@ -250,7 +250,7 @@ class GistsController(BaseController):
 
        success = True
 
        revision = request.POST.get('revision')
 

	
 
        ##TODO: maybe move this to model ?
 
        # TODO: maybe move this to model ?
 
        if revision != last_rev.raw_id:
 
            log.error('Last revision %s is different than submitted %s',
 
                      revision, last_rev)
kallithea/controllers/admin/my_account.py
Show inline comments
 
@@ -131,7 +131,7 @@ class MyAccountController(BaseController
 
                    force_defaults=False)
 
            except Exception:
 
                log.error(traceback.format_exc())
 
                h.flash(_('Error occurred during update of user %s') \
 
                h.flash(_('Error occurred during update of user %s')
 
                        % form_result.get('username'), category='error')
 
        if update:
 
            raise HTTPFound(location='my_account')
kallithea/controllers/admin/repo_groups.py
Show inline comments
 
@@ -177,7 +177,7 @@ class RepoGroupsController(BaseControlle
 
                force_defaults=False)
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('Error occurred during creation of repository group %s') \
 
            h.flash(_('Error occurred during creation of repository group %s')
 
                    % request.POST.get('group_name'), category='error')
 
            parent_group_id = form_result['parent_group_id']
 
            #TODO: maybe we should get back to the main view, not the admin one
 
@@ -229,7 +229,7 @@ class RepoGroupsController(BaseControlle
 

	
 
            new_gr = RepoGroupModel().update(group_name, form_result)
 
            Session().commit()
 
            h.flash(_('Updated repository group %s') \
 
            h.flash(_('Updated repository group %s')
 
                    % form_result['group_name'], category='success')
 
            # we now have new name !
 
            group_name = new_gr.group_name
 
@@ -245,7 +245,7 @@ class RepoGroupsController(BaseControlle
 
                force_defaults=False)
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('Error occurred during update of repository group %s') \
 
            h.flash(_('Error occurred during update of repository group %s')
 
                    % request.POST.get('group_name'), category='error')
 

	
 
        raise HTTPFound(location=url('edit_repo_group', group_name=group_name))
kallithea/controllers/admin/repos.py
Show inline comments
 
@@ -257,7 +257,7 @@ class ReposController(BaseRepoController
 

	
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('Error occurred during update of repository %s') \
 
            h.flash(_('Error occurred during update of repository %s')
 
                    % repo_name, category='error')
 
        raise HTTPFound(location=url('edit_repo', repo_name=changed_name))
 

	
 
@@ -456,7 +456,6 @@ class ReposController(BaseRepoController
 
                    category='error')
 
        raise HTTPFound(location=url('edit_repo_advanced', repo_name=repo_name))
 

	
 

	
 
    @HasRepoPermissionLevelDecorator('admin')
 
    def edit_advanced_fork(self, repo_name):
 
        """
kallithea/controllers/admin/settings.py
Show inline comments
 
@@ -160,7 +160,7 @@ class SettingsController(BaseController)
 
        if request.POST:
 
            rm_obsolete = request.POST.get('destroy', False)
 
            install_git_hooks = request.POST.get('hooks', False)
 
            overwrite_git_hooks = request.POST.get('hooks_overwrite', False);
 
            overwrite_git_hooks = request.POST.get('hooks_overwrite', False)
 
            invalidate_cache = request.POST.get('invalidate', False)
 
            log.debug('rescanning repo location with destroy obsolete=%s, '
 
                      'install git hooks=%s and '
kallithea/controllers/admin/user_groups.py
Show inline comments
 
@@ -155,7 +155,7 @@ class UserGroupsController(BaseControlle
 
                force_defaults=False)
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('Error occurred during creation of user group %s') \
 
            h.flash(_('Error occurred during creation of user group %s')
 
                    % request.POST.get('users_group_name'), category='error')
 

	
 
        raise HTTPFound(location=url('users_groups'))
 
@@ -205,7 +205,7 @@ class UserGroupsController(BaseControlle
 
                force_defaults=False)
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('Error occurred during update of user group %s') \
 
            h.flash(_('Error occurred during update of user group %s')
 
                    % request.POST.get('users_group_name'), category='error')
 

	
 
        raise HTTPFound(location=url('edit_users_group', id=id))
 
@@ -415,7 +415,6 @@ class UserGroupsController(BaseControlle
 
                                     key=lambda u: u.username.lower())
 
        return render('admin/user_groups/user_group_edit.html')
 

	
 

	
 
    @HasUserGroupPermissionLevelDecorator('admin')
 
    def edit_members(self, id):
 
        c.user_group = UserGroup.get_or_404(id)
kallithea/controllers/admin/users.py
Show inline comments
 
@@ -137,7 +137,7 @@ class UsersController(BaseController):
 
            h.flash(e, 'error')
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('Error occurred during creation of user %s') \
 
            h.flash(_('Error occurred during creation of user %s')
 
                    % request.POST.get('username'), category='error')
 
        raise HTTPFound(location=url('edit_user', id=user.user_id))
 

	
 
@@ -180,7 +180,7 @@ class UsersController(BaseController):
 
                force_defaults=False)
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            h.flash(_('Error occurred during update of user %s') \
 
            h.flash(_('Error occurred during update of user %s')
 
                    % form_result.get('username'), category='error')
 
        raise HTTPFound(location=url('edit_user', id=id))
 

	
kallithea/controllers/root.py
Show inline comments
 
@@ -17,6 +17,7 @@ from kallithea.lib.base import BaseContr
 
from kallithea.controllers.error import ErrorController
 
from tg import config
 

	
 

	
 
# This is the main Kallithea entry point; TurboGears will forward all requests
 
# to an instance of 'controller.root.RootController' in the configured
 
# 'application' module (set by app_cfg.py).  Requests are forwarded to
kallithea/lib/annotate.py
Show inline comments
 
@@ -149,7 +149,7 @@ class AnnotateHtmlFormatter(HtmlFormatte
 
            for i in range(fl, fl + lncount):
 
                if i % st == 0:
 
                    if aln:
 
                        lines.append('<a href="#%s-%d">%*d</a>' \
 
                        lines.append('<a href="#%s-%d">%*d</a>'
 
                                     % (la, i, mw, i))
 
                    else:
 
                        lines.append('%*d' % (mw, i))
kallithea/lib/auth.py
Show inline comments
 
@@ -104,7 +104,7 @@ def get_crypt_password(password):
 
        import bcrypt
 
        return bcrypt.hashpw(safe_str(password), bcrypt.gensalt(10))
 
    else:
 
        raise Exception('Unknown or unsupported platform %s' \
 
        raise Exception('Unknown or unsupported platform %s'
 
                        % __platform__)
 

	
 

	
 
@@ -129,7 +129,7 @@ def check_password(password, hashed):
 
            log.error('error from bcrypt checking password: %s', e)
 
            return False
 
    else:
 
        raise Exception('Unknown or unsupported platform %s' \
 
        raise Exception('Unknown or unsupported platform %s'
 
                        % __platform__)
 

	
 

	
 
@@ -261,7 +261,7 @@ def _cached_perms_data(user_id, user_is_
 
    for gr, perms in _grouped:
 
        # since user can be in multiple groups iterate over them and
 
        # select the lowest permissions first (more explicit)
 
        ##TODO: do this^^
 
        # TODO: do this^^
 
        if not gr.inherit_default_permissions:
 
            # NEED TO IGNORE all configurable permissions and
 
            # replace them with explicitly set
kallithea/lib/auth_modules/__init__.py
Show inline comments
 
@@ -76,7 +76,6 @@ class KallitheaAuthPluginBase(object):
 
                #log.debug('Initializing lazy formencode object: %s', obj)
 
                return LazyFormencode(obj, *args, **kwargs)
 

	
 

	
 
        class ProxyGet(object):
 
            def __getattribute__(self, name):
 
                return LazyCaller(name)
 
@@ -420,6 +419,7 @@ def authenticate(username, password, env
 
                        username, module)
 
    return None
 

	
 

	
 
def get_managed_fields(user):
 
    """return list of fields that are managed by the user's auth source, usually some of
 
    'username', 'firstname', 'lastname', 'email', 'active', 'password'
kallithea/lib/caching_query.py
Show inline comments
 
@@ -220,8 +220,8 @@ def _params_from_query(query):
 

	
 
    """
 
    v = []
 

	
 
    def visit_bindparam(bind):
 

	
 
        if bind.key in query._params:
 
            value = query._params[bind.key]
 
        elif bind.callable:
kallithea/lib/celerylib/__init__.py
Show inline comments
 
@@ -74,6 +74,7 @@ def task(f_org):
 
        f_async.__name__ = f_org.__name__
 
        from kallithea.lib import celerypylons
 
        runner = celerypylons.task(ignore_result=True)(f_async)
 

	
 
        def f_wrapped(*args, **kwargs):
 
            t = runner.apply_async(args=args, kwargs=kwargs)
 
            log.info('executing task %s in async mode - id %s', f_org, t.task_id)
kallithea/lib/celerylib/tasks.py
Show inline comments
 
@@ -321,6 +321,7 @@ def send_email(recipients, subject, body
 
        return False
 
    return True
 

	
 

	
 
@celerylib.task
 
@celerylib.dbsession
 
def create_repo(form_data, cur_user):
kallithea/lib/celerypylons/__init__.py
Show inline comments
 
@@ -27,7 +27,9 @@ def celery_config(config):
 
    # Verify .ini file configuration has been loaded
 
    assert config['celery.imports'] == 'kallithea.lib.celerylib.tasks', 'Kallithea Celery configuration has not been loaded'
 

	
 
    class CeleryConfig(object): pass
 
    class CeleryConfig(object):
 
        pass
 

	
 
    celery_config = CeleryConfig()
 

	
 
    PREFIXES = """ADMINS BROKER CASSANDRA CELERYBEAT CELERYD CELERYMON CELERY EMAIL SERVER""".split()
kallithea/lib/compat.py
Show inline comments
 
@@ -55,6 +55,7 @@ else:
 

	
 
# Python Software Foundation License
 

	
 

	
 
# XXX: it feels like using the class with "is" and "is not" instead of "==" and
 
# "!=" should be faster.
 
class _Nil(object):
 
@@ -74,6 +75,7 @@ class _Nil(object):
 
        else:
 
            return NotImplemented
 

	
 

	
 
_nil = _Nil()
 

	
 

	
kallithea/lib/dbmigrate/__init__.py
Show inline comments
 
from gearbox.command import Command
 

	
 

	
 
class UpgradeDb(Command):
 
    '''(removed)'''
 

	
kallithea/lib/diffs.py
Show inline comments
 
@@ -130,6 +130,7 @@ def get_gitdiff(filenode_old, filenode_n
 
                                ignore_whitespace, context)
 
    return vcs_gitdiff
 

	
 

	
 
NEW_FILENODE = 1
 
DEL_FILENODE = 2
 
MOD_FILENODE = 3
 
@@ -205,7 +206,6 @@ class DiffProcessor(object):
 

	
 
    _escape_re = re.compile(r'(&)|(<)|(>)|(\t)|(\r)|(?<=.)( \n| $)')
 

	
 

	
 
    def __init__(self, diff, vcs='hg', format='gitdiff', diff_limit=None):
 
        """
 
        :param diff:   a text in diff format
 
@@ -383,7 +383,7 @@ class DiffProcessor(object):
 
        _files = []
 
        diff_container = lambda arg: arg
 

	
 
        ##split the diff in chunks of separate --git a/file b/file chunks
 
        # split the diff in chunks of separate --git a/file b/file chunks
 
        for raw_diff in ('\n' + self._diff).split('\ndiff --git')[1:]:
 
            head, diff = self._get_header(raw_diff)
 

	
kallithea/lib/ext_json.py
Show inline comments
 
@@ -22,6 +22,7 @@ def _is_tz_aware(value):
 
    return (value.tzinfo is not None
 
            and value.tzinfo.utcoffset(value) is not None)
 

	
 

	
 
def _obj_dump(obj):
 
    """
 
    Custom function for dumping objects to JSON, if obj has __json__ attribute
kallithea/lib/graphmod.py
Show inline comments
 
@@ -19,6 +19,7 @@ It allows to have a shared codebase for 
 

	
 
nullrev = -1
 

	
 

	
 
def _first_known_ancestors(parentrev_func, minrev, knownrevs, head):
 
    """
 
    Return the apparent parents of the head revision in a filtered DAG.
 
@@ -45,6 +46,7 @@ def _first_known_ancestors(parentrev_fun
 
            seen.add(r)
 
    return ancestors
 

	
 

	
 
def graph_data(repo, revs):
 
    """Return a DAG with colored edge information for revs
 

	
 
@@ -61,6 +63,7 @@ def graph_data(repo, revs):
 
    dag = _dagwalker(repo, revs)
 
    return list(_colored(repo, dag))
 

	
 

	
 
def _dagwalker(repo, revs):
 
    """Iterate over revs, yielding revs (highest first) and parents to show in the graph."""
 
    if not revs:
 
@@ -102,6 +105,7 @@ def _colored(repo, dag):
 
        parents.
 
    """
 
    branch_cache = {}
 

	
 
    def branch(rev):
 
        """Return branch for rev, using cache for efficiency.
 
        For Mercurial, always return the named branch name (which may be 'default').
kallithea/lib/helpers.py
Show inline comments
 
@@ -64,6 +64,7 @@ def canonical_url(*args, **kargs):
 
        kargs['qualified'] = True
 
    return url(*args, **kargs)
 

	
 

	
 
def canonical_hostname():
 
    '''Return canonical hostname of system'''
 
    from kallithea import CONFIG
 
@@ -74,6 +75,7 @@ def canonical_hostname():
 
        parts = url('home', qualified=True).split('://', 1)
 
        return parts[1].split('/', 1)[0]
 

	
 

	
 
def html_escape(s):
 
    """Return string with all html escaped.
 
    This is also safe for javascript in html but not necessarily correct.
 
@@ -116,6 +118,7 @@ def js(value):
 
        .replace('>', r'\x3e')
 
    )
 

	
 

	
 
def jshtml(val):
 
    """HTML escapes a string value, then converts the resulting string
 
    to its corresponding JavaScript representation (see `js`).
 
@@ -150,6 +153,7 @@ def _reset(name, value=None, id=NotGiven
 
    convert_boolean_attrs(attrs, ["disabled"])
 
    return HTML.input(**attrs)
 

	
 

	
 
reset = _reset
 
safeid = _make_safe_id_component
 

	
 
@@ -190,6 +194,7 @@ class _FilesBreadCrumbs(object):
 

	
 
        return literal('/'.join(url_l))
 

	
 

	
 
files_breadcrumbs = _FilesBreadCrumbs()
 

	
 

	
 
@@ -272,6 +277,7 @@ class CodeHtmlFormatter(HtmlFormatter):
 

	
 
_whitespace_re = re.compile(r'(\t)|( )(?=\n|</div>)')
 

	
 

	
 
def _markup_whitespace(m):
 
    groups = m.groups()
 
    if groups[0]:
 
@@ -279,9 +285,11 @@ def _markup_whitespace(m):
 
    if groups[1]:
 
        return ' <i></i>'
 

	
 

	
 
def markup_whitespace(s):
 
    return _whitespace_re.sub(_markup_whitespace, s)
 

	
 

	
 
def pygmentize(filenode, **kwargs):
 
    """
 
    pygmentize function using pygments
 
@@ -399,6 +407,7 @@ class _Message(object):
 
    def __html__(self):
 
        return escape(safe_unicode(self.message))
 

	
 

	
 
class Flash(_Flash):
 

	
 
    def __call__(self, message, category=None, ignore_duplicate=False, logf=None):
 
@@ -430,6 +439,7 @@ class Flash(_Flash):
 
        session.save()
 
        return [_Message(*m) for m in messages]
 

	
 

	
 
flash = Flash()
 

	
 
#==============================================================================
 
@@ -499,6 +509,7 @@ def user_or_none(author):
 
        return User.get_by_email(email, cache=True) # cache will only use sql_cache_short
 
    return None
 

	
 

	
 
def email_or_none(author):
 
    """Try to match email part of VCS committer string with a local user.
 
    Return primary email of user, email part of the specified author name, or None."""
 
@@ -516,6 +527,7 @@ def email_or_none(author):
 
    # No valid email, not a valid user in the system, none!
 
    return None
 

	
 

	
 
def person(author, show_attr="username"):
 
    """Find the user identified by 'author', return one of the users attributes,
 
    default to the username attribute, None if there is no user"""
 
@@ -848,6 +860,7 @@ def gravatar_div(email_address, cls='', 
 
                   (''.join(attributes),
 
                    gravatar(email_address, cls=cls, size=size)))
 

	
 

	
 
def gravatar(email_address, cls='', size=30):
 
    """return html element of the gravatar
 

	
 
@@ -875,6 +888,7 @@ def gravatar(email_address, cls='', size
 

	
 
    return literal(html)
 

	
 

	
 
def gravatar_url(email_address, size=30, default=''):
 
    # doh, we need to re-import those to mock it later
 
    from kallithea.config.routing import url
 
@@ -1013,7 +1027,6 @@ _URLIFY_RE = re.compile(r'''
 
    re.VERBOSE | re.MULTILINE | re.IGNORECASE)
 

	
 

	
 

	
 
def urlify_text(s, repo_name=None, link_=None, truncate=None, stylize=False, truncatef=truncate):
 
    """
 
    Parses given text message and make literal html with markup.
 
@@ -1131,6 +1144,7 @@ def urlify_issues(newtext, repo_name):
 

	
 
            # Wrap tmp_urlify_issues_f with substitution of this pattern, while making sure all loop variables (and compiled regexpes) are bound
 
            issue_re = re.compile(issue_pat)
 

	
 
            def issues_replace(match_obj,
 
                               issue_server_link=issue_server_link, issue_prefix=issue_prefix):
 
                leadingspace = ' ' if match_obj.group().startswith(' ') else ''
 
@@ -1174,6 +1188,7 @@ def short_ref(ref_type, ref_name):
 
        return short_id(ref_name)
 
    return ref_name
 

	
 

	
 
def link_to_ref(repo_name, ref_type, ref_name, rev=None):
 
    """
 
    Return full markup for a href to changeset_home for a changeset.
 
@@ -1191,6 +1206,7 @@ def link_to_ref(repo_name, ref_type, ref
 
        l = literal('%s (%s)' % (l, link_to(short_id(rev), url('changeset_home', repo_name=repo_name, revision=rev))))
 
    return l
 

	
 

	
 
def changeset_status(repo, revision):
 
    from kallithea.model.changeset_status import ChangesetStatusModel
 
    return ChangesetStatusModel().get_status(repo, revision)
kallithea/lib/ipaddr.py
Show inline comments
 
@@ -367,9 +367,11 @@ def collapse_address_list(addresses):
 
    return _collapse_address_list_recursive(sorted(
 
        addrs + nets, key=_BaseNet._get_networks_key))
 

	
 

	
 
# backwards compatibility
 
CollapseAddrList = collapse_address_list
 

	
 

	
 
# We need to distinguish between the string and packed-bytes representations
 
# of an IP address.  For example, b'0::1' is the IPv4 address 48.58.58.49,
 
# while '0::1' is an IPv6 address.
kallithea/lib/markup_renderer.py
Show inline comments
 
@@ -79,6 +79,7 @@ class MarkupRenderer(object):
 

	
 
        # Extract pre blocks.
 
        extractions = {}
 

	
 
        def pre_extraction_callback(matchobj):
 
            digest = md5(matchobj.group(0)).hexdigest()
 
            extractions[digest] = matchobj.group(0)
kallithea/lib/middleware/sessionmiddleware.py
Show inline comments
 
@@ -26,6 +26,7 @@ Original Beaker SessionMiddleware class 
 
from beaker.session import SessionObject
 
from beaker.middleware import SessionMiddleware
 

	
 

	
 
class SecureSessionMiddleware(SessionMiddleware):
 
    def __call__(self, environ, start_response):
 
        """
kallithea/lib/middleware/simplehg.py
Show inline comments
 
@@ -62,6 +62,7 @@ def is_mercurial(environ):
 
    )
 
    return ishg_path
 

	
 

	
 
class SimpleHg(BaseVCSController):
 

	
 
    def _handle_request(self, environ, start_response):
kallithea/lib/page.py
Show inline comments
 
@@ -21,6 +21,7 @@ from kallithea.config.routing import url
 
from webhelpers.html import literal, HTML
 
from webhelpers.paginate import Page as _Page
 

	
 

	
 
class Page(_Page):
 
    """
 
    Custom pager to match rendering style with YUI paginator emitting Bootstrap paginators
kallithea/lib/paster_commands/install_iis.py
Show inline comments
 
@@ -61,6 +61,7 @@ if __name__=='__main__':
 
    HandleCommandLine(params)
 
'''
 

	
 

	
 
class Command(BasePasterCommand):
 
    '''Kallithea: Install into IIS using isapi-wsgi'''
 

	
kallithea/lib/rcmail/response.py
Show inline comments
 
@@ -196,7 +196,7 @@ class MailResponse(object):
 
        self.attachments.append({'filename': filename,
 
                                 'content_type': content_type,
 
                                 'data': data,
 
                                 'disposition': disposition,})
 
                                 'disposition': disposition})
 

	
 
    def attach_part(self, part):
 
        """
kallithea/lib/rcmail/utils.py
Show inline comments
 
@@ -16,4 +16,5 @@ class CachedDnsName(object):
 
            self._fqdn = socket.getfqdn()
 
        return self._fqdn
 

	
 

	
 
DNS_NAME = CachedDnsName()
kallithea/lib/utils.py
Show inline comments
 
@@ -479,7 +479,7 @@ def repo2db_mapper(initial_repo_list, re
 
        user = User.get_first_admin()
 
    added = []
 

	
 
    ##creation defaults
 
    # creation defaults
 
    defs = Setting.get_default_repo_settings(strip_prefix=True)
 
    enable_statistics = defs.get('repo_enable_statistics')
 
    enable_locking = defs.get('repo_enable_locking')
kallithea/lib/utils2.py
Show inline comments
 
@@ -531,6 +531,7 @@ def time_to_datetime(tm):
 
# Matching is greedy so we don't have to look beyond the end.
 
MENTIONS_REGEX = re.compile(r'(?:^|(?<=[^a-zA-Z0-9]))@([a-zA-Z0-9][-_.a-zA-Z0-9]*[a-zA-Z0-9])')
 

	
 

	
 
def extract_mentioned_usernames(text):
 
    r"""
 
    Returns list of (possible) usernames @mentioned in given text.
 
@@ -540,6 +541,7 @@ def extract_mentioned_usernames(text):
 
    """
 
    return MENTIONS_REGEX.findall(text)
 

	
 

	
 
def extract_mentioned_users(text):
 
    """ Returns set of actual database Users @mentioned in given text. """
 
    from kallithea.model.db import User
 
@@ -649,6 +651,7 @@ class OptionalAttr(object):
 
    def __call__(self):
 
        return self
 

	
 

	
 
#alias
 
OAttr = OptionalAttr
 

	
 
@@ -697,5 +700,6 @@ class Optional(object):
 
            return val.getval()
 
        return val
 

	
 

	
 
def urlreadable(s, _cleanstringsub=re.compile('[^-a-zA-Z0-9./]+').sub):
 
    return _cleanstringsub('_', safe_str(s)).rstrip('_')
kallithea/lib/vcs/backends/base.py
Show inline comments
 
@@ -700,6 +700,7 @@ class BaseChangeset(object):
 
    def phase(self):
 
        return ''
 

	
 

	
 
class BaseWorkdir(object):
 
    """
 
    Working directory representation of single repository.
kallithea/lib/vcs/backends/git/repository.py
Show inline comments
 
@@ -527,7 +527,7 @@ class GitRepository(BaseRepository):
 

	
 
        """
 
        if branch_name and branch_name not in self.branches:
 
            raise BranchDoesNotExistError("Branch '%s' not found" \
 
            raise BranchDoesNotExistError("Branch '%s' not found"
 
                                          % branch_name)
 
        # actually we should check now if it's not an empty repo to not spaw
 
        # subprocess commands
kallithea/lib/vcs/backends/hg/changeset.py
Show inline comments
 
@@ -18,6 +18,7 @@ from kallithea.lib.vcs.utils.hgcompat im
 

	
 
from mercurial import obsolete
 

	
 

	
 
class MercurialChangeset(BaseChangeset):
 
    """
 
    Represents state of the repository at the single revision.
kallithea/lib/vcs/subprocessio.py
Show inline comments
 
@@ -45,7 +45,7 @@ class StreamFeeder(threading.Thread):
 
            self.bytes = bytes(source)
 
        else:  # can be either file pointer or file-like
 
            if type(source) in (int, long):  # file pointer it is
 
                ## converting file descriptor (int) stdin into file-like
 
                # converting file descriptor (int) stdin into file-like
 
                source = os.fdopen(source, 'rb', 16384)
 
            # let's see if source is file-like by now
 
            filelike = hasattr(source, 'read')
kallithea/lib/vcs/utils/__init__.py
Show inline comments
 
@@ -157,6 +157,7 @@ email_re = re.compile(
 
    r"""(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?""",
 
    re.IGNORECASE)
 

	
 

	
 
def author_email(author):
 
    """
 
    Returns email address of given author string.
kallithea/lib/vcs/utils/annotate.py
Show inline comments
 
@@ -122,7 +122,7 @@ class AnnotateHtmlFormatter(HtmlFormatte
 
            for i in range(fl, fl + lncount):
 
                if i % st == 0:
 
                    if aln:
 
                        lines.append('<a href="#%s-%d">%*d</a>' \
 
                        lines.append('<a href="#%s-%d">%*d</a>'
 
                                     % (la, i, mw, i))
 
                    else:
 
                        lines.append('%*d' % (mw, i))
kallithea/lib/vcs/utils/hgcompat.py
Show inline comments
 
@@ -4,7 +4,7 @@ Mercurial libs compatibility
 

	
 
import mercurial
 
import mercurial.demandimport
 
## patch demandimport, due to bug in mercurial when it always triggers demandimport.enable()
 
# patch demandimport, due to bug in mercurial when it always triggers demandimport.enable()
 
mercurial.demandimport.enable = lambda *args, **kwargs: 1
 
from mercurial import archival, merge as hg_merge, patch, ui
 
from mercurial import discovery
 
@@ -38,6 +38,7 @@ import inspect
 
# Mercurial 3.1 503bb3af70fe
 
if inspect.getargspec(memfilectx.__init__).args[1] != 'repo':
 
    _org__init__=memfilectx.__init__
 

	
 
    def _memfilectx__init__(self, repo, *a, **b):
 
        return _org__init__(self, *a, **b)
 
    memfilectx.__init__ = _memfilectx__init__
kallithea/lib/vcs/utils/lazy.py
Show inline comments
 
@@ -9,6 +9,7 @@ class _Missing(object):
 
    def __reduce__(self):
 
        return '_missing'
 

	
 

	
 
_missing = _Missing()
 

	
 

	
kallithea/lib/vcs/utils/progressbar.py
Show inline comments
 
@@ -10,6 +10,7 @@ from kallithea.lib.vcs.utils.helpers imp
 
class ProgressBarError(Exception):
 
    pass
 

	
 

	
 
class AlreadyFinishedError(ProgressBarError):
 
    pass
 

	
 
@@ -179,6 +180,7 @@ background = dict([(color_names[x], '4%s
 
RESET = '0'
 
opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'}
 

	
 

	
 
def colorize(text='', opts=(), **kwargs):
 
    """
 
    Returns your text, enclosed in ANSI graphics codes.
 
@@ -223,6 +225,7 @@ def colorize(text='', opts=(), **kwargs)
 
        text = text + '\x1b[%sm' % RESET
 
    return ('\x1b[%sm' % ';'.join(code_list)) + text
 

	
 

	
 
def make_style(opts=(), **kwargs):
 
    """
 
    Returns a function with default parameters for colorize()
 
@@ -235,6 +238,7 @@ def make_style(opts=(), **kwargs):
 
    """
 
    return lambda text: colorize(text, opts, **kwargs)
 

	
 

	
 
NOCOLOR_PALETTE = 'nocolor'
 
DARK_PALETTE = 'dark'
 
LIGHT_PALETTE = 'light'
 
@@ -348,7 +352,6 @@ class BarOnlyColoredProgressBar(ColoredP
 
    pass
 

	
 

	
 

	
 
def main():
 
    import time
 

	
kallithea/lib/vcs/utils/termcolors.py
Show inline comments
 
@@ -11,6 +11,7 @@ background = dict([(color_names[x], '4%s
 
RESET = '0'
 
opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'}
 

	
 

	
 
def colorize(text='', opts=(), **kwargs):
 
    """
 
    Returns your text, enclosed in ANSI graphics codes.
 
@@ -55,6 +56,7 @@ def colorize(text='', opts=(), **kwargs)
 
        text = text + '\x1b[%sm' % RESET
 
    return ('\x1b[%sm' % ';'.join(code_list)) + text
 

	
 

	
 
def make_style(opts=(), **kwargs):
 
    """
 
    Returns a function with default parameters for colorize()
 
@@ -67,6 +69,7 @@ def make_style(opts=(), **kwargs):
 
    """
 
    return lambda text: colorize(text, opts, **kwargs)
 

	
 

	
 
NOCOLOR_PALETTE = 'nocolor'
 
DARK_PALETTE = 'dark'
 
LIGHT_PALETTE = 'light'
 
@@ -120,6 +123,7 @@ PALETTES = {
 
}
 
DEFAULT_PALETTE = DARK_PALETTE
 

	
 

	
 
def parse_color_setting(config_string):
 
    """Parse a DJANGO_COLORS environment variable to produce the system palette
 

	
kallithea/lib/verlib.py
Show inline comments
 
@@ -5,10 +5,12 @@ discussion at PyCon 2009.
 

	
 
import re
 

	
 

	
 
class IrrationalVersionError(Exception):
 
    """This is an irrational version."""
 
    pass
 

	
 

	
 
class HugeMajorVersionNumError(IrrationalVersionError):
 
    """An irrational version because the major version number is huge
 
    (often because a year or date was used).
 
@@ -18,6 +20,7 @@ class HugeMajorVersionNumError(Irrationa
 
    """
 
    pass
 

	
 

	
 
# A marker used in the second and third parts of the `parts` tuple, for
 
# versions that don't have those segments, to sort properly. An example
 
# of versions in sort order ('highest' last):
 
@@ -47,6 +50,7 @@ VERSION_RE = re.compile(r'''
 
    (?P<postdev>(\.post(?P<post>\d+))?(\.dev(?P<dev>\d+))?)?
 
    $''', re.VERBOSE)
 

	
 

	
 
class NormalizedVersion(object):
 
    """A rational version.
 

	
 
@@ -212,6 +216,7 @@ class NormalizedVersion(object):
 
    def __ge__(self, other):
 
        return self.__eq__(other) or self.__gt__(other)
 

	
 

	
 
def suggest_normalized_version(s):
 
    """Suggest a normalized version close to the given version string.
 

	
 
@@ -313,7 +318,6 @@ def suggest_normalized_version(s):
 
    # PyPI stats: ~21 (0.62%) better
 
    rs = re.sub(r"\.?(pre|preview|-c)(\d+)$", r"c\g<2>", rs)
 

	
 

	
 
    # Tcl/Tk uses "px" for their post release markers
 
    rs = re.sub(r"p(\d+)$", r".post\1", rs)
 

	
kallithea/model/comment.py
Show inline comments
 
@@ -128,7 +128,7 @@ class ChangesetCommentsModel(object):
 
            comment_url = pull_request.url(canonical=True,
 
                anchor='comment-%s' % comment.comment_id)
 
            subj = safe_unicode(
 
                h.link_to('Re pull request %(pr_nice_id)s: %(desc)s %(line)s' % \
 
                h.link_to('Re pull request %(pr_nice_id)s: %(desc)s %(line)s' %
 
                          {'desc': desc,
 
                           'pr_nice_id': comment.pull_request.nice_id(),
 
                           'line': line},
kallithea/model/db.py
Show inline comments
 
@@ -462,7 +462,6 @@ class User(Base, BaseDbModel):
 
    #extra API keys
 
    user_api_keys = relationship('UserApiKeys', cascade='all')
 

	
 

	
 
    @hybrid_property
 
    def email(self):
 
        return self._email
 
@@ -801,6 +800,7 @@ class UserIpMap(Base, BaseDbModel):
 
        return u"<%s('user_id:%s=>%s')>" % (self.__class__.__name__,
 
                                            self.user_id, self.ip_addr)
 

	
 

	
 
class UserLog(Base, BaseDbModel):
 
    __tablename__ = 'user_logs'
 
    __table_args__ = (
 
@@ -2455,6 +2455,7 @@ class PullRequest(Base, BaseDbModel):
 
        return h.url('pullrequest_show', repo_name=self.other_repo.repo_name,
 
                     pull_request_id=self.pull_request_id, **kwargs)
 

	
 

	
 
class PullRequestReviewer(Base, BaseDbModel):
 
    __tablename__ = 'pull_request_reviewers'
 
    __table_args__ = (
kallithea/model/forms.py
Show inline comments
 
@@ -90,6 +90,7 @@ def PasswordChangeForm(username):
 

	
 
def UserForm(edit=False, old_data=None):
 
    old_data = old_data or {}
 

	
 
    class _UserForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = True
 
@@ -131,6 +132,7 @@ def UserForm(edit=False, old_data=None):
 
def UserGroupForm(edit=False, old_data=None, available_members=None):
 
    old_data = old_data or {}
 
    available_members = available_members or []
 

	
 
    class _UserGroupForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = True
 
@@ -158,6 +160,7 @@ def RepoGroupForm(edit=False, old_data=N
 
    old_data = old_data or {}
 
    repo_groups = repo_groups or []
 
    repo_group_ids = [rg[0] for rg in repo_groups]
 

	
 
    class _RepoGroupForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = False
 
@@ -219,6 +222,7 @@ def PasswordResetRequestForm():
 
        email = v.Email(not_empty=True)
 
    return _PasswordResetRequestForm
 

	
 

	
 
def PasswordResetConfirmationForm():
 
    class _PasswordResetConfirmationForm(formencode.Schema):
 
        allow_extra_fields = True
 
@@ -234,12 +238,14 @@ def PasswordResetConfirmationForm():
 
                                                    'password_confirm')]
 
    return _PasswordResetConfirmationForm
 

	
 

	
 
def RepoForm(edit=False, old_data=None, supported_backends=BACKENDS.keys(),
 
             repo_groups=None, landing_revs=None):
 
    old_data = old_data or {}
 
    repo_groups = repo_groups or []
 
    landing_revs = landing_revs or []
 
    repo_group_ids = [rg[0] for rg in repo_groups]
 

	
 
    class _RepoForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = False
 
@@ -317,6 +323,7 @@ def RepoForkForm(edit=False, old_data=No
 
    repo_groups = repo_groups or []
 
    landing_revs = landing_revs or []
 
    repo_group_ids = [rg[0] for rg in repo_groups]
 

	
 
    class _RepoForkForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = False
kallithea/model/meta.py
Show inline comments
 
@@ -38,7 +38,7 @@ Session = scoped_session(session_factory
 
# Engine is injected when model.__init__.init_model() sets meta.Base.metadata.bind
 
Base = declarative_base()
 

	
 
#to use cache use this in query
 
# to use cache use this in query:
 
#.options(FromCache("sqlalchemy_cache_type", "cachekey"))
 

	
 

	
kallithea/model/notification.py
Show inline comments
 
@@ -108,7 +108,7 @@ class NotificationModel(object):
 

	
 
        # send email with notification to all other participants
 
        for rec in rec_objs:
 
            ## this is passed into template
 
            # this is passed into template
 
            html_kwargs = {
 
                      'subject': subject,
 
                      'body': h.render_w_mentions(body, repo_name),
kallithea/model/repo_group.py
Show inline comments
 
@@ -125,7 +125,7 @@ class RepoGroupModel(object):
 
            if force_delete:
 
                shutil.rmtree(rm_path)
 
            else:
 
                #archive that group`
 
                # archive that group
 
                _now = datetime.datetime.now()
 
                _ms = str(_now.microsecond).rjust(6, '0')
 
                _d = 'rm__%s_GROUP_%s' % (_now.strftime('%Y%m%d_%H%M%S_' + _ms),
kallithea/model/scm.py
Show inline comments
 
@@ -776,6 +776,7 @@ class ScmModel(object):
 
            else:
 
                log.debug('skipping writing hook file')
 

	
 

	
 
def AvailableRepoGroupChoices(top_perms, repo_group_perm_level, extras=()):
 
    """Return group_id,string tuples with choices for all the repo groups where
 
    the user has the necessary permissions.
kallithea/model/validators.py
Show inline comments
 
@@ -68,6 +68,7 @@ def UniqueListFromString():
 

	
 
def ValidUsername(edit=False, old_data=None):
 
    old_data = old_data or {}
 

	
 
    class _validator(formencode.validators.FancyValidator):
 
        messages = {
 
            'username_exists': _('Username "%(username)s" already exists'),
 
@@ -126,6 +127,7 @@ def ValidRepoUser():
 

	
 
def ValidUserGroup(edit=False, old_data=None):
 
    old_data = old_data or {}
 

	
 
    class _validator(formencode.validators.FancyValidator):
 
        messages = {
 
            'invalid_group': _('Invalid user group name'),
kallithea/tests/base.py
Show inline comments
 
@@ -54,7 +54,7 @@ __all__ = [
 
# Invoke websetup with the current config file
 
# SetupCommand('setup-app').run([config_file])
 

	
 
#SOME GLOBALS FOR TESTS
 
## SOME GLOBALS FOR TESTS
 

	
 
TESTS_TMP_PATH = os.environ.get('KALLITHEA_TESTS_TMP_PATH', tempfile.mkdtemp(prefix='kallithea-test-'))
 
os.environ['VCS_TEST_ROOT'] = TESTS_TMP_PATH
 
@@ -123,6 +123,7 @@ try:
 
except ImportError:
 
    pam_lib_installed = False
 

	
 

	
 
def invalidate_all_caches():
 
    """Invalidate all beaker caches currently configured.
 
    Useful when manipulating IP permissions in a test and changes need to take
 
@@ -133,10 +134,12 @@ def invalidate_all_caches():
 
    for cache in cache_managers.values():
 
        cache.clear()
 

	
 

	
 
class NullHandler(logging.Handler):
 
    def emit(self, record):
 
        pass
 

	
 

	
 
class TestController(object):
 
    """Pytest-style test controller"""
 

	
kallithea/tests/conftest.py
Show inline comments
 
@@ -23,6 +23,7 @@ import kallithea.tests.base # FIXME: nee
 

	
 
from tg.util.webtest import test_context
 

	
 

	
 
def pytest_configure():
 
    os.environ['TZ'] = 'UTC'
 
    if not kallithea.is_windows:
 
@@ -70,10 +71,12 @@ def pytest_configure():
 
    # set fixed language for form messages, regardless of environment settings
 
    formencode.api.set_stdtranslation(languages=[])
 

	
 

	
 
@pytest.fixture
 
def create_test_user():
 
    """Provide users that automatically disappear after test is over."""
 
    test_user_ids = []
 

	
 
    def _create_test_user(user_form):
 
        user = UserModel().create(user_form)
 
        test_user_ids.append(user.user_id)
 
@@ -115,6 +118,7 @@ def set_test_settings():
 
        Setting.create_or_update(k, v, t)
 
    session.commit()
 

	
 

	
 
@pytest.fixture
 
def auto_clear_ip_permissions():
 
    """Fixture that provides nothing but clearing IP permissions upon test
 
@@ -135,6 +139,7 @@ def auto_clear_ip_permissions():
 
    # IP permissions are cached, need to invalidate this cache explicitly
 
    invalidate_all_caches()
 

	
 

	
 
@pytest.fixture
 
def test_context_fixture(app_fixture):
 
    """
 
@@ -177,6 +182,7 @@ class MyWSGIServer(WSGIServer):
 
            auth += '@'
 
        return '%s://%s%s:%s/%s' % (proto, auth, host, port, repo_name)
 

	
 

	
 
@pytest.yield_fixture(scope="session")
 
def webserver():
 
    """Start web server while tests are running.
kallithea/tests/fixture.py
Show inline comments
 
@@ -257,7 +257,7 @@ class Fixture(object):
 
            'owner': TEST_USER_ADMIN_LOGIN,
 
            'gist_type': Gist.GIST_PUBLIC,
 
            'lifetime': -1,
 
            'gist_mapping': {'filename1.txt':{'content':'hello world'},}
 
            'gist_mapping': {'filename1.txt': {'content': 'hello world'}}
 
        }
 
        form_data.update(kwargs)
 
        gist = GistModel().create(
kallithea/tests/functional/test_admin_auth_settings.py
Show inline comments
 
@@ -164,7 +164,6 @@ class TestAuthSettingsController(TestCon
 
        assert response.form['firstname'].value == 'John'
 
        assert response.form['lastname'].value == 'Doe'
 

	
 

	
 
    def test_container_auth_login_fallback_header(self):
 
        self._container_auth_setup(
 
            auth_container_header='THE_USER_NAME',
kallithea/tests/functional/test_admin_notifications.py
Show inline comments
 
@@ -8,6 +8,7 @@ from kallithea.lib import helpers as h
 

	
 
from tg.util.webtest import test_context
 

	
 

	
 
class TestNotificationsController(TestController):
 
    def setup_method(self, method):
 
        self.remove_all_notifications()
kallithea/tests/functional/test_admin_permissions.py
Show inline comments
 
@@ -74,7 +74,6 @@ class TestAdminPermissionsController(Tes
 
        response.mustcontain(no=['127.0.0.0/24'])
 
        response.mustcontain(no=['127.0.0.0 - 127.0.0.255'])
 

	
 

	
 
    def test_index_overview(self):
 
        self.log_user()
 
        response = self.app.get(url('admin_permissions_perms'))
kallithea/tests/functional/test_admin_repo_groups.py
Show inline comments
 
@@ -7,6 +7,7 @@ from kallithea.tests.fixture import Fixt
 

	
 
fixture = Fixture()
 

	
 

	
 
class TestRepoGroupsController(TestController):
 

	
 
    def test_case_insensitivity(self):
kallithea/tests/functional/test_admin_repos.py
Show inline comments
 
@@ -332,7 +332,6 @@ class _BaseTestCase(TestController):
 
                                                _authentication_token=self.authentication_token()))
 
        response.mustcontain('Invalid repository URL')
 

	
 

	
 
    def test_create_remote_repo_wrong_clone_uri_hg_svn(self):
 
        self.log_user()
 
        repo_name = self.NEW_REPO
 
@@ -346,7 +345,6 @@ class _BaseTestCase(TestController):
 
                                                _authentication_token=self.authentication_token()))
 
        response.mustcontain('Invalid repository URL')
 

	
 

	
 
    def test_delete(self):
 
        self.log_user()
 
        repo_name = u'vcs_test_new_to_delete_%s' % self.REPO_TYPE
kallithea/tests/functional/test_admin_users.py
Show inline comments
 
@@ -30,6 +30,7 @@ from tg.util.webtest import test_context
 

	
 
fixture = Fixture()
 

	
 

	
 
@pytest.fixture
 
def user_and_repo_group_fail():
 
    username = 'repogrouperr'
 
@@ -44,6 +45,7 @@ def user_and_repo_group_fail():
 
        # delete already succeeded in test body
 
        pass
 

	
 

	
 
class TestAdminUsersController(TestController):
 
    test_user_1 = 'testme'
 

	
 
@@ -164,9 +166,8 @@ class TestAdminUsersController(TestContr
 
        if name == 'extern_name':
 
            #cannot update this via form, expected value is original one
 
            params['extern_name'] = self.test_user_1
 
            # special case since this user is not
 
                                          # logged in yet his data is not filled
 
                                          # so we use creation data
 
            # special case since this user is not logged in yet his data is
 
            # not filled so we use creation data
 

	
 
        params.update({'_authentication_token': self.authentication_token()})
 
        response = self.app.post(url('update_user', id=usr.user_id), params)
kallithea/tests/functional/test_compare.py
Show inline comments
 
@@ -6,6 +6,7 @@ from kallithea.tests.fixture import Fixt
 

	
 
fixture = Fixture()
 

	
 

	
 
def _commit_ref(repo_name, sha, msg):
 
    return '''<div class="message-firstline"><a class="message-link" href="/%s/changeset/%s">%s</a></div>''' % (repo_name, sha, msg)
 

	
 
@@ -245,7 +246,7 @@ class TestCompareController(TestControll
 
        response.mustcontain("""<a class="btn btn-default btn-sm" href="/%s/compare/branch@%s...branch@%s?other_repo=%s&amp;merge=True"><i class="icon-arrows-cw"></i> Swap</a>""" % (repo2.repo_name, rev1, rev2, repo1.repo_name))
 

	
 
    def test_compare_cherry_pick_changesets_from_bottom(self):
 

	
 
        pass
 
#        repo1:
 
#            cs0:
 
#            cs1:
 
@@ -313,6 +314,7 @@ class TestCompareController(TestControll
 
        response.mustcontain("""#C--826e8142e6ba">file1</a>""")
 

	
 
    def test_compare_cherry_pick_changesets_from_top(self):
 
        pass
 
#        repo1:
 
#            cs0:
 
#            cs1:
kallithea/tests/functional/test_feed.py
Show inline comments
 
@@ -7,8 +7,6 @@ class TestFeedController(TestController)
 
        response = self.app.get(url(controller='feed', action='rss',
 
                                    repo_name=HG_REPO))
 

	
 

	
 

	
 
        assert response.content_type == "application/rss+xml"
 
        assert """<rss version="2.0">""" in response
 

	
kallithea/tests/functional/test_forks.py
Show inline comments
 
@@ -14,6 +14,7 @@ from kallithea.model.meta import Session
 

	
 
fixture = Fixture()
 

	
 

	
 
class _BaseTestCase(TestController):
 
    """
 
    Write all tests here
 
@@ -34,7 +35,6 @@ class _BaseTestCase(TestController):
 
        Session().delete(self.u1)
 
        Session().commit()
 

	
 

	
 
    def test_index(self):
 
        self.log_user()
 
        repo_name = self.REPO
kallithea/tests/functional/test_my_account.py
Show inline comments
 
@@ -234,7 +234,6 @@ class TestMyAccountController(TestContro
 
        keys = UserApiKeys.query().all()
 
        assert 0 == len(keys)
 

	
 

	
 
    def test_my_account_reset_main_api_key(self):
 
        usr = self.log_user(TEST_USER_REGULAR2_LOGIN, TEST_USER_REGULAR2_PASS)
 
        user = User.get(usr['user_id'])
kallithea/tests/functional/test_pullrequests.py
Show inline comments
 
@@ -12,6 +12,7 @@ from kallithea.controllers.pullrequests 
 

	
 
fixture = Fixture()
 

	
 

	
 
class TestPullrequestsController(TestController):
 

	
 
    def test_index(self):
 
@@ -208,7 +209,6 @@ class TestPullrequestsController(TestCon
 
                                 status=400)
 
        response.mustcontain('Invalid reviewer &#34;%s&#34; specified' % invalid_user_id)
 

	
 

	
 
    def test_iteration_refs(self):
 
        # Repo graph excerpt:
 
        #   o   fb95b340e0d0 webvcs
kallithea/tests/functional/test_search_indexing.py
Show inline comments
 
@@ -10,6 +10,7 @@ from kallithea.tests.fixture import crea
 

	
 
fixture = Fixture()
 

	
 

	
 
def init_indexing_test(repo):
 
    prev = fixture.commit_change(repo.repo_name,
 
                                 filename='this_should_be_unique_filename.txt',
 
@@ -34,6 +35,7 @@ def init_stopword_test(repo):
 
                                 parent=prev,
 
                                 newfile=True)
 

	
 

	
 
repos = [
 
    # reponame,              init func or fork base, groupname
 
    (u'indexing_test',       init_indexing_test,     None),
 
@@ -44,10 +46,12 @@ repos = [
 
    (u'stopword_test',       init_stopword_test,     None),
 
]
 

	
 

	
 
# map: name => id
 
repoids = {}
 
groupids = {}
 

	
 

	
 
def rebuild_index(full_index):
 
    with mock.patch('kallithea.lib.indexers.daemon.log.debug',
 
                    lambda *args, **kwargs: None):
kallithea/tests/models/test_changeset_status.py
Show inline comments
 
@@ -2,11 +2,13 @@ from kallithea.tests.base import *
 
from kallithea.model.changeset_status import ChangesetStatusModel
 
from kallithea.model.db import ChangesetStatus as CS
 

	
 

	
 
class CSM(object): # ChangesetStatusMock
 

	
 
    def __init__(self, status):
 
        self.status = status
 

	
 

	
 
class TestChangesetStatusCalculation(TestController):
 

	
 
    def setup_method(self, method):
kallithea/tests/models/test_notifications.py
Show inline comments
 
@@ -16,6 +16,7 @@ import kallithea.lib.celerylib.tasks
 

	
 
from tg.util.webtest import test_context
 

	
 

	
 
class TestNotifications(TestController):
 

	
 
    def setup_method(self, method):
 
@@ -48,6 +49,7 @@ class TestNotifications(TestController):
 
    def test_create_notification(self):
 
        with test_context(self.app):
 
            usrs = [self.u1, self.u2]
 

	
 
            def send_email(recipients, subject, body='', html_body='', headers=None, author=None):
 
                assert recipients == ['u2@example.com']
 
                assert subject == 'Test Message'
kallithea/tests/models/test_settings.py
Show inline comments
 
@@ -4,6 +4,7 @@ from kallithea.model.db import Setting
 

	
 
name = 'spam-setting-name'
 

	
 

	
 
def test_passing_list_setting_value_results_in_string_valued_setting():
 
    assert Setting.get_by_name(name) is None
 
    setting = Setting.create_or_update(name, ['spam', 'eggs'])
 
@@ -17,6 +18,7 @@ def test_passing_list_setting_value_resu
 
    finally:
 
        Session().delete(setting)
 

	
 

	
 
def test_list_valued_setting_creation_requires_manual_value_formatting():
 
    assert Setting.get_by_name(name) is None
 
    # Quirk: need manual formatting of list setting value.
 
@@ -27,6 +29,7 @@ def test_list_valued_setting_creation_re
 
    finally:
 
        Session().delete(setting)
 

	
 

	
 
def test_list_valued_setting_update():
 
    assert Setting.get_by_name(name) is None
 
    setting = Setting.create_or_update(name, 'spam', type='list')
kallithea/tests/models/test_users.py
Show inline comments
 
@@ -4,7 +4,6 @@ from kallithea.tests.base import *
 
from kallithea.model.db import User, UserGroup, UserGroupMember, UserEmailMap, \
 
    Permission
 
from kallithea.model.user import UserModel
 

	
 
from kallithea.model.meta import Session
 
from kallithea.model.user_group import UserGroupModel
 
from kallithea.tests.fixture import Fixture
kallithea/tests/other/test_libs.py
Show inline comments
 
@@ -67,6 +67,7 @@ TEST_URLS += [
 
     '%s://example.com:8080' % proto),
 
]
 

	
 

	
 
class FakeUrlGenerator(object):
 

	
 
    def __init__(self, current_url=None, default_route=None, **routes):
 
@@ -86,6 +87,7 @@ class FakeUrlGenerator(object):
 
    def current(self, *args, **kwargs):
 
        return self.current_url % kwargs
 

	
 

	
 
class TestLibs(TestController):
 

	
 
    @parametrize('test_url,expected,expected_creds', TEST_URLS)
kallithea/tests/other/test_mail.py
Show inline comments
 
@@ -4,6 +4,7 @@ import kallithea
 
from kallithea.tests.base import *
 
from kallithea.model.db import User
 

	
 

	
 
class smtplib_mock(object):
 

	
 
    @classmethod
 
@@ -12,14 +13,17 @@ class smtplib_mock(object):
 

	
 
    def ehlo(self):
 
        pass
 

	
 
    def quit(self):
 
        pass
 

	
 
    def sendmail(self, sender, dest, msg):
 
        smtplib_mock.lastsender = sender
 
        smtplib_mock.lastdest = dest
 
        smtplib_mock.lastmsg = msg
 
        pass
 

	
 

	
 
@mock.patch('kallithea.lib.rcmail.smtp_mailer.smtplib', smtplib_mock)
 
class TestMail(TestController):
 

	
kallithea/tests/performance/test_vcs.py
Show inline comments
 
@@ -13,6 +13,7 @@
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
import pytest
 

	
 
from kallithea.model.db import Repository
 
from kallithea.tests.base import *
 

	
kallithea/tests/scripts/manual_test_concurrency.py
Show inline comments
 
@@ -186,6 +186,7 @@ def test_clone_with_credentials(no_error
 
            elif backend == 'git':
 
                assert """Cloning into""" in stdout, 'no messages about cloning'
 

	
 

	
 
if __name__ == '__main__':
 
    try:
 
        create_test_user(force=False)
kallithea/tests/vcs/__init__.py
Show inline comments
 
@@ -61,5 +61,6 @@ def main():
 
    collector()
 
    unittest.main()
 

	
 

	
 
#if __name__ == '__main__':
 
#    main()
kallithea/tests/vcs/test_archives.py
Show inline comments
 
@@ -100,6 +100,7 @@ class ArchivesTestCaseMixin(_BackendTest
 
        with self.assertRaises(VCSError):
 
            self.tip.fill_archive(prefix='/any')
 

	
 

	
 
# For each backend create test case class
 
for alias in SCM_TESTS:
 
    attrs = {
kallithea/tests/vcs/test_changesets.py
Show inline comments
 
@@ -49,6 +49,7 @@ class TestBaseChangeset(unittest.TestCas
 
            'removed': [],
 
        })
 

	
 

	
 
class _ChangesetsWithCommitsTestCaseixin(_BackendTestMixin):
 
    recreate_repo_per_test = True
 

	
 
@@ -365,6 +366,7 @@ class _ChangesetsChangesTestCaseMixin(_B
 
        self.assertEqual(33188, changeset.get_file_mode('foo/bał'))
 
        self.assertEqual(33188, changeset.get_file_mode(u'foo/bał'))
 

	
 

	
 
# For each backend create test case class
 
for alias in SCM_TESTS:
 
    attrs = {
kallithea/tests/vcs/test_git.py
Show inline comments
 
@@ -170,8 +170,6 @@ class GitRepositoryTest(unittest.TestCas
 
            'e686b958768ee96af8029fe19c6050b1a8dd3b2b'])
 
        self.assertTrue(subset.issubset(set(self.repo.revisions)))
 

	
 

	
 

	
 
    def test_slicing(self):
 
        #4 1 5 10 95
 
        for sfrom, sto, size in [(0, 4, 4), (1, 2, 1), (10, 15, 5),
 
@@ -181,7 +179,6 @@ class GitRepositoryTest(unittest.TestCas
 
            self.assertEqual(revs[0], self.repo.get_changeset(sfrom))
 
            self.assertEqual(revs[-1], self.repo.get_changeset(sto - 1))
 

	
 

	
 
    def test_branches(self):
 
        # TODO: Need more tests here
 
        # Removed (those are 'remotes' branches for cloned repo)
 
@@ -370,7 +367,6 @@ class GitChangesetTest(unittest.TestCase
 
                'vcs/backends/hg.py', 854),
 
            ('6e125e7c890379446e98980d8ed60fba87d0f6d1',
 
                'setup.py', 1068),
 

	
 
            ('d955cd312c17b02143c04fa1099a352b04368118',
 
                'vcs/backends/base.py', 2921),
 
            ('ca1eb7957a54bce53b12d1a51b13452f95bc7c7e',
kallithea/tests/vcs/test_hg.py
Show inline comments
 
@@ -98,7 +98,6 @@ class MercurialRepositoryTest(unittest.T
 
                ])
 
        self.assertTrue(subset.issubset(set(self.repo.revisions)))
 

	
 

	
 
        # check if we have the proper order of revisions
 
        org = ['b986218ba1c9b0d6a259fac9b050b1724ed8e545',
 
                '3d8f361e72ab303da48d799ff1ac40d5ac37c67e',
 
@@ -462,7 +461,7 @@ class MercurialChangesetTest(unittest.Te
 
        self.assertEqual(set((node.path for node in chset88.changed)),
 
            set(['.hgignore']))
 
        self.assertEqual(set((node.path for node in chset88.removed)), set())
 
#
 

	
 
        # 85:
 
        #    added:   2 ['vcs/utils/diffs.py', 'vcs/web/simplevcs/views/diffs.py']
 
        #    changed: 4 ['vcs/web/simplevcs/models.py', ...]
 
@@ -536,7 +535,6 @@ class MercurialChangesetTest(unittest.Te
 
        path = 'foo/bar/setup.py'
 
        self.assertRaises(VCSError, self.repo.get_changeset().get_node, path)
 

	
 

	
 
    def test_archival_file(self):
 
        #TODO:
 
        pass
 
@@ -553,7 +551,6 @@ class MercurialChangesetTest(unittest.Te
 
        #TODO:
 
        pass
 

	
 

	
 
    def test_author_email(self):
 
        self.assertEqual('marcin@python-blog.com',
 
                         self.repo.get_changeset('b986218ba1c9').author_email)
kallithea/tests/vcs/test_nodes.py
Show inline comments
 
@@ -170,6 +170,7 @@ class NodeBasicTest(unittest.TestCase):
 
        self.assertEqual(my_node3.mimetype, 'application/octet-stream')
 
        self.assertEqual(my_node3.get_mimetype(), ('application/octet-stream', None))
 

	
 

	
 
class NodeContentTest(unittest.TestCase):
 

	
 
    def test_if_binary(self):
kallithea/tests/vcs/test_tags.py
Show inline comments
 
@@ -46,6 +46,7 @@ class TagsTestCaseMixin(_BackendTestMixi
 
        self.repo.tag('11', 'joe')
 
        self.assertTrue('11' in self.repo.tags)
 

	
 

	
 
# For each backend create test case class
 
for alias in SCM_TESTS:
 
    attrs = {
kallithea/tests/vcs/test_utils.py
Show inline comments
 
@@ -43,7 +43,6 @@ class PathsTest(unittest.TestCase):
 
        for path, expected in paths_and_results:
 
            self._test_get_dirs_for_path(path, expected)
 

	
 

	
 
    def test_get_scm(self):
 
        self.assertEqual(('hg', TEST_HG_REPO), get_scm(TEST_HG_REPO))
 
        self.assertEqual(('git', TEST_GIT_REPO), get_scm(TEST_GIT_REPO))
 
@@ -209,13 +208,10 @@ class TestAuthorExtractors(unittest.Test
 
                  ]
 

	
 
    def test_author_email(self):
 

	
 
        for test_str, result in self.TEST_AUTHORS:
 
            self.assertEqual(result[1], author_email(test_str))
 

	
 

	
 
    def test_author_name(self):
 

	
 
        for test_str, result in self.TEST_AUTHORS:
 
            self.assertEqual(result[0], author_name(test_str))
 

	
kallithea/tests/vcs/test_vcs.py
Show inline comments
 

	
 
import os
 
import shutil
 

	
 
@@ -9,7 +8,6 @@ from kallithea.lib.vcs.utils.compat impo
 
from kallithea.tests.vcs.conf import TEST_HG_REPO, TEST_GIT_REPO, TEST_TMP_PATH
 

	
 

	
 

	
 
class VCSTest(unittest.TestCase):
 
    """
 
    Tests for main module's methods.
 
@@ -64,7 +62,6 @@ class VCSTest(unittest.TestCase):
 
        self.assertEqual(repo.__class__, get_repo(safe_str(path)).__class__)
 
        self.assertEqual(repo.path, get_repo(safe_str(path)).path)
 

	
 

	
 
    def test_get_repo_err(self):
 
        blank_repo_path = os.path.join(TEST_TMP_PATH, 'blank-error-repo')
 
        if os.path.isdir(blank_repo_path):
0 comments (0 inline, 0 general)