diff --git a/kallithea/bin/base.py b/kallithea/bin/base.py
--- a/kallithea/bin/base.py
+++ b/kallithea/bin/base.py
@@ -158,7 +158,7 @@ class RcConf(object):
"""
try:
with open(self._conf_name, 'rb') as conf:
- return json.load(conf)
+ return json.load(conf)
except IOError as e:
#sys.stderr.write(str(e) + '\n')
pass
diff --git a/kallithea/bin/kallithea_api.py b/kallithea/bin/kallithea_api.py
--- a/kallithea/bin/kallithea_api.py
+++ b/kallithea/bin/kallithea_api.py
@@ -121,5 +121,6 @@ def main(argv=None):
)
return 0
+
if __name__ == '__main__':
sys.exit(main(sys.argv))
diff --git a/kallithea/bin/kallithea_backup.py b/kallithea/bin/kallithea_backup.py
--- a/kallithea/bin/kallithea_backup.py
+++ b/kallithea/bin/kallithea_backup.py
@@ -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'
diff --git a/kallithea/config/app_cfg.py b/kallithea/config/app_cfg.py
--- a/kallithea/config/app_cfg.py
+++ b/kallithea/config/app_cfg.py
@@ -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)
diff --git a/kallithea/config/middleware.py b/kallithea/config/middleware.py
--- a/kallithea/config/middleware.py
+++ b/kallithea/config/middleware.py
@@ -23,10 +23,12 @@ from kallithea.config.environment import
# 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
diff --git a/kallithea/config/post_receive_tmpl.py b/kallithea/config/post_receive_tmpl.py
--- a/kallithea/config/post_receive_tmpl.py
+++ b/kallithea/config/post_receive_tmpl.py
@@ -25,5 +25,6 @@ def main():
_handler(repo_path, push_data, os.environ)
sys.exit(0)
+
if __name__ == '__main__':
main()
diff --git a/kallithea/config/pre_receive_tmpl.py b/kallithea/config/pre_receive_tmpl.py
--- a/kallithea/config/pre_receive_tmpl.py
+++ b/kallithea/config/pre_receive_tmpl.py
@@ -25,5 +25,6 @@ def main():
_handler(repo_path, push_data, os.environ)
sys.exit(0)
+
if __name__ == '__main__':
main()
diff --git a/kallithea/config/rcextensions/__init__.py b/kallithea/config/rcextensions/__init__.py
--- a/kallithea/config/rcextensions/__init__.py
+++ b/kallithea/config/rcextensions/__init__.py
@@ -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
diff --git a/kallithea/config/routing.py b/kallithea/config/routing.py
--- a/kallithea/config/routing.py
+++ b/kallithea/config/routing.py
@@ -94,7 +94,7 @@ def make_map(config):
# CUSTOM ROUTES HERE
#==========================================================================
- #MAIN PAGE
+ # MAIN PAGE
rmap.connect('home', '/', controller='home', action='index')
rmap.connect('about', '/about', controller='home', action='about')
rmap.connect('repo_switcher_data', '/_repos', controller='home',
@@ -106,7 +106,7 @@ def make_map(config):
rmap.connect('kallithea_project_url', "https://kallithea-scm.org/", _static=True)
rmap.connect('issues_url', 'https://bitbucket.org/conservancy/kallithea/issues', _static=True)
- #ADMIN REPOSITORY ROUTES
+ # ADMIN REPOSITORY ROUTES
with rmap.submapper(path_prefix=ADMIN_PREFIX,
controller='admin/repos') as m:
m.connect("repos", "/repos",
@@ -121,7 +121,7 @@ def make_map(config):
m.connect("delete_repo", "/repos/{repo_name:.*?}/delete",
action="delete", conditions=dict(method=["POST"]))
- #ADMIN REPOSITORY GROUPS ROUTES
+ # ADMIN REPOSITORY GROUPS ROUTES
with rmap.submapper(path_prefix=ADMIN_PREFIX,
controller='admin/repo_groups') as m:
m.connect("repos_groups", "/repo_groups",
@@ -138,7 +138,7 @@ def make_map(config):
action="show", conditions=dict(method=["GET"],
function=check_group))
- #EXTRAS REPO GROUP ROUTES
+ # EXTRAS REPO GROUP ROUTES
m.connect("edit_repo_group", "/repo_groups/{group_name:.*?}/edit",
action="edit",
conditions=dict(method=["GET"], function=check_group))
@@ -161,8 +161,7 @@ def make_map(config):
action="delete", conditions=dict(method=["POST"],
function=check_group_skip_path))
-
- #ADMIN USER ROUTES
+ # ADMIN USER ROUTES
with rmap.submapper(path_prefix=ADMIN_PREFIX,
controller='admin/users') as m:
m.connect("new_user", "/users/new",
@@ -180,7 +179,7 @@ def make_map(config):
m.connect("edit_user", "/users/{id}/edit",
action="edit", conditions=dict(method=["GET"]))
- #EXTRAS USER ROUTES
+ # EXTRAS USER ROUTES
m.connect("edit_user_advanced", "/users/{id}/edit/advanced",
action="edit_advanced", conditions=dict(method=["GET"]))
@@ -210,7 +209,7 @@ def make_map(config):
m.connect("edit_user_ips_delete", "/users/{id}/edit/ips/delete",
action="delete_ip", conditions=dict(method=["POST"]))
- #ADMIN USER GROUPS REST ROUTES
+ # ADMIN USER GROUPS REST ROUTES
with rmap.submapper(path_prefix=ADMIN_PREFIX,
controller='admin/user_groups') as m:
m.connect("users_groups", "/user_groups",
@@ -227,13 +226,12 @@ def make_map(config):
action="edit", conditions=dict(method=["GET"]),
function=check_user_group)
- #EXTRAS USER GROUP ROUTES
+ # EXTRAS USER GROUP ROUTES
m.connect("edit_user_group_default_perms", "/user_groups/{id}/edit/default_perms",
action="edit_default_perms", conditions=dict(method=["GET"]))
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,9 +245,7 @@ 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
+ # ADMIN PERMISSIONS ROUTES
with rmap.submapper(path_prefix=ADMIN_PREFIX,
controller='admin/permissions') as m:
m.connect("admin_permissions", "/permissions",
@@ -263,8 +259,7 @@ def make_map(config):
m.connect("admin_permissions_perms", "/permissions/perms",
action="permission_perms", conditions=dict(method=["GET"]))
-
- #ADMIN DEFAULTS ROUTES
+ # ADMIN DEFAULTS ROUTES
with rmap.submapper(path_prefix=ADMIN_PREFIX,
controller='admin/defaults') as m:
m.connect('defaults', 'defaults',
@@ -272,14 +267,14 @@ def make_map(config):
m.connect('defaults_update', 'defaults/{id}/update',
action="update", conditions=dict(method=["POST"]))
- #ADMIN AUTH SETTINGS
+ # ADMIN AUTH SETTINGS
rmap.connect('auth_settings', '%s/auth' % ADMIN_PREFIX,
controller='admin/auth_settings', action='auth_settings',
conditions=dict(method=["POST"]))
rmap.connect('auth_home', '%s/auth' % ADMIN_PREFIX,
controller='admin/auth_settings')
- #ADMIN SETTINGS ROUTES
+ # ADMIN SETTINGS ROUTES
with rmap.submapper(path_prefix=ADMIN_PREFIX,
controller='admin/settings') as m:
m.connect("admin_settings", "/settings",
@@ -326,7 +321,7 @@ def make_map(config):
m.connect("admin_settings_system_update", "/settings/system/updates",
action="settings_system_update", conditions=dict(method=["GET"]))
- #ADMIN MY ACCOUNT
+ # ADMIN MY ACCOUNT
with rmap.submapper(path_prefix=ADMIN_PREFIX,
controller='admin/my_account') as m:
@@ -363,7 +358,7 @@ def make_map(config):
m.connect("my_account_api_keys_delete", "/my_account/api_keys/delete",
action="my_account_api_keys_delete", conditions=dict(method=["POST"]))
- #NOTIFICATION REST ROUTES
+ # NOTIFICATION REST ROUTES
with rmap.submapper(path_prefix=ADMIN_PREFIX,
controller='admin/notifications') as m:
m.connect("notifications", "/notifications",
@@ -381,7 +376,7 @@ def make_map(config):
m.connect("formatted_notification", "/notifications/{notification_id}.{format}",
action="show", conditions=dict(method=["GET"]))
- #ADMIN GIST
+ # ADMIN GIST
with rmap.submapper(path_prefix=ADMIN_PREFIX,
controller='admin/gists') as m:
m.connect("gists", "/gists",
@@ -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}",
@@ -412,7 +405,7 @@ def make_map(config):
revision='tip',
action="show", conditions=dict(method=["GET"]))
- #ADMIN MAIN PAGES
+ # ADMIN MAIN PAGES
with rmap.submapper(path_prefix=ADMIN_PREFIX,
controller='admin/admin') as m:
m.connect('admin_home', '', action='index')
@@ -425,7 +418,7 @@ def make_map(config):
action='_dispatch') as m:
m.connect('api', '/api')
- #USER JOURNAL
+ # USER JOURNAL
rmap.connect('journal', '%s/journal' % ADMIN_PREFIX,
controller='journal', action='index')
rmap.connect('journal_rss', '%s/journal/rss' % ADMIN_PREFIX,
@@ -454,7 +447,7 @@ def make_map(config):
controller='journal', action='toggle_following',
conditions=dict(method=["POST"]))
- #SEARCH
+ # SEARCH
rmap.connect('search', '%s/search' % ADMIN_PREFIX, controller='search',)
rmap.connect('search_repo_admin', '%s/search/{repo_name:.*}' % ADMIN_PREFIX,
controller='search',
@@ -464,7 +457,7 @@ def make_map(config):
conditions=dict(function=check_repo),
)
- #LOGIN/LOGOUT/REGISTER/SIGN IN
+ # LOGIN/LOGOUT/REGISTER/SIGN IN
rmap.connect('authentication_token', '%s/authentication_token' % ADMIN_PREFIX, controller='login', action='authentication_token')
rmap.connect('login_home', '%s/login' % ADMIN_PREFIX, controller='login')
rmap.connect('logout_home', '%s/logout' % ADMIN_PREFIX, controller='login',
@@ -480,7 +473,7 @@ def make_map(config):
'%s/password_reset_confirmation' % ADMIN_PREFIX,
controller='login', action='password_reset_confirmation')
- #FEEDS
+ # FEEDS
rmap.connect('rss_feed_home', '/{repo_name:.*?}/feed/rss',
controller='feed', action='rss',
conditions=dict(function=check_repo))
@@ -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))
@@ -594,7 +584,7 @@ def make_map(config):
controller='admin/repos', action="edit_statistics",
conditions=dict(method=["POST"], function=check_repo))
- #still working url for backward compat.
+ # still working url for backward compat.
rmap.connect('raw_changeset_home_depraced',
'/{repo_name:.*?}/raw-changeset/{revision}',
controller='changeset', action='changeset_raw',
@@ -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()
diff --git a/kallithea/controllers/admin/admin.py b/kallithea/controllers/admin/admin.py
--- a/kallithea/controllers/admin/admin.py
+++ b/kallithea/controllers/admin/admin.py
@@ -65,11 +65,11 @@ def _journal_filter(user_log, search_ter
def wildcard_handler(col, wc_term):
if wc_term.startswith('*') and not wc_term.endswith('*'):
- #postfix == endswith
+ # postfix == endswith
wc_term = remove_prefix(wc_term, prefix='*')
return func.lower(col).endswith(func.lower(wc_term))
elif wc_term.startswith('*') and wc_term.endswith('*'):
- #wildcard == ilike
+ # wildcard == ilike
wc_term = remove_prefix(wc_term, prefix='*')
wc_term = remove_suffix(wc_term, suffix='*')
return func.lower(col).contains(func.lower(wc_term))
@@ -88,7 +88,7 @@ def _journal_filter(user_log, search_ter
field = getattr(UserLog, field)
log.debug('filter field: %s val=>%s', field, val)
- #sql filtering
+ # sql filtering
if isinstance(term, query.Wildcard):
return wildcard_handler(field, val)
elif isinstance(term, query.Prefix):
@@ -130,7 +130,7 @@ class AdminController(BaseController):
.options(joinedload(UserLog.user)) \
.options(joinedload(UserLog.repository))
- #FILTERING
+ # FILTERING
c.search_term = request.GET.get('filter')
users_log = _journal_filter(users_log, c.search_term)
diff --git a/kallithea/controllers/admin/gists.py b/kallithea/controllers/admin/gists.py
--- a/kallithea/controllers/admin/gists.py
+++ b/kallithea/controllers/admin/gists.py
@@ -106,7 +106,7 @@ class GistsController(BaseController):
gist_form = GistForm([x[0] for x in c.lifetime_values])()
try:
form_result = gist_form.to_python(dict(request.POST))
- #TODO: multiple files support, from the form
+ # TODO: multiple files support, from the form
filename = form_result['filename'] or Gist.DEFAULT_FILENAME
nodes = {
filename: {
@@ -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)
diff --git a/kallithea/controllers/admin/my_account.py b/kallithea/controllers/admin/my_account.py
--- a/kallithea/controllers/admin/my_account.py
+++ b/kallithea/controllers/admin/my_account.py
@@ -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')
@@ -173,7 +173,7 @@ class MyAccountController(BaseController
c.active = 'repos'
self.__load_data()
- #data used to render the grid
+ # data used to render the grid
c.data = self._load_my_repos_data()
return render('admin/my_account/my_account.html')
@@ -181,7 +181,7 @@ class MyAccountController(BaseController
c.active = 'watched'
self.__load_data()
- #data used to render the grid
+ # data used to render the grid
c.data = self._load_my_repos_data(watched=True)
return render('admin/my_account/my_account.html')
diff --git a/kallithea/controllers/admin/repo_groups.py b/kallithea/controllers/admin/repo_groups.py
--- a/kallithea/controllers/admin/repo_groups.py
+++ b/kallithea/controllers/admin/repo_groups.py
@@ -166,7 +166,7 @@ class RepoGroupsController(BaseControlle
copy_permissions=form_result['group_copy_permissions']
)
Session().commit()
- #TODO: in future action_logger(, '', '', '')
+ # TODO: in future action_logger(, '', '', '')
except formencode.Invalid as errors:
return htmlfill.render(
render('admin/repo_groups/repo_group_add.html'),
@@ -177,10 +177,10 @@ 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
+ # TODO: maybe we should get back to the main view, not the admin one
raise HTTPFound(location=url('repos_groups', parent_group=parent_group_id))
h.flash(_('Created repository group %s') % gr.group_name,
category='success')
@@ -188,7 +188,7 @@ class RepoGroupsController(BaseControlle
def new(self):
if HasPermissionAny('hg.admin')('group create'):
- #we're global admin, we're ok and we can create TOP level groups
+ # we're global admin, we're ok and we can create TOP level groups
pass
else:
# we pass in parent group into creation form, thus we know
@@ -212,7 +212,7 @@ class RepoGroupsController(BaseControlle
# TODO: kill allow_empty_group - it is only used for redundant form validation!
if HasPermissionAny('hg.admin')('group edit'):
- #we're global admin, we're ok and we can create TOP level groups
+ # we're global admin, we're ok and we can create TOP level groups
allow_empty_group = True
elif not c.repo_group.parent_group:
allow_empty_group = True
@@ -229,11 +229,11 @@ 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
- #TODO: in future action_logger(, '', '', '')
+ # TODO: in future action_logger(, '', '', '')
except formencode.Invalid as errors:
c.active = 'settings'
return htmlfill.render(
@@ -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))
@@ -270,7 +270,7 @@ class RepoGroupsController(BaseControlle
Session().commit()
h.flash(_('Removed repository group %s') % group_name,
category='success')
- #TODO: in future action_logger(, '', '', '')
+ # TODO: in future action_logger(, '', '', '')
except Exception:
log.error(traceback.format_exc())
h.flash(_('Error occurred during deletion of repository group %s')
@@ -369,7 +369,7 @@ class RepoGroupsController(BaseControlle
form_result['perms_new'],
form_result['perms_updates'],
recursive)
- #TODO: implement this
+ # TODO: implement this
#action_logger(request.authuser, 'admin_changed_repo_permissions',
# repo_name, request.ip_addr)
Session().commit()
diff --git a/kallithea/controllers/admin/repos.py b/kallithea/controllers/admin/repos.py
--- a/kallithea/controllers/admin/repos.py
+++ b/kallithea/controllers/admin/repos.py
@@ -104,7 +104,7 @@ class ReposController(BaseRepoController
repos_data = RepoModel().get_repos_as_dict(repos_list=c.repos_list,
admin=True,
super_user_actions=True)
- #data used to render the grid
+ # data used to render the grid
c.data = repos_data
return render('admin/repos/repos.html')
@@ -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))
@@ -331,7 +331,7 @@ class ReposController(BaseRepoController
form = RepoPermsForm()().to_python(request.POST)
RepoModel()._update_permissions(repo_name, form['perms_new'],
form['perms_updates'])
- #TODO: implement this
+ # TODO: implement this
#action_logger(request.authuser, 'admin_changed_repo_permissions',
# repo_name, request.ip_addr)
Session().commit()
@@ -353,7 +353,7 @@ class ReposController(BaseRepoController
RepoModel().revoke_user_group_permission(
repo=repo_name, group_name=obj_id
)
- #TODO: implement this
+ # TODO: implement this
#action_logger(request.authuser, 'admin_revoked_repo_permissions',
# repo_name, request.ip_addr)
Session().commit()
@@ -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):
"""
diff --git a/kallithea/controllers/admin/settings.py b/kallithea/controllers/admin/settings.py
--- a/kallithea/controllers/admin/settings.py
+++ b/kallithea/controllers/admin/settings.py
@@ -102,7 +102,7 @@ class SettingsController(BaseController)
sett = Ui.get_by_key('paths', '/')
sett.ui_value = form_result['paths_root_path']
- #HOOKS
+ # HOOKS
sett = Ui.get_by_key('hooks', Ui.HOOK_UPDATE)
sett.ui_active = form_result['hooks_changegroup_update']
@@ -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 '
diff --git a/kallithea/controllers/admin/user_groups.py b/kallithea/controllers/admin/user_groups.py
--- a/kallithea/controllers/admin/user_groups.py
+++ b/kallithea/controllers/admin/user_groups.py
@@ -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))
@@ -283,7 +283,7 @@ class UserGroupsController(BaseControlle
except RepoGroupAssignmentError:
h.flash(_('Target group cannot be the same'), category='error')
raise HTTPFound(location=url('edit_user_group_perms', id=id))
- #TODO: implement this
+ # TODO: implement this
#action_logger(request.authuser, 'admin_changed_repo_permissions',
# repo_name, request.ip_addr)
Session().commit()
@@ -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)
diff --git a/kallithea/controllers/admin/users.py b/kallithea/controllers/admin/users.py
--- a/kallithea/controllers/admin/users.py
+++ b/kallithea/controllers/admin/users.py
@@ -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))
diff --git a/kallithea/controllers/changelog.py b/kallithea/controllers/changelog.py
--- a/kallithea/controllers/changelog.py
+++ b/kallithea/controllers/changelog.py
@@ -114,7 +114,7 @@ class ChangelogController(BaseRepoContro
try:
collection = tip_cs.get_file_history(f_path)
except (NodeDoesNotExistError, ChangesetError):
- #this node is not present at tip !
+ # this node is not present at tip !
try:
cs = self.__get_cs(revision, repo_name)
collection = cs.get_file_history(f_path)
diff --git a/kallithea/controllers/changeset.py b/kallithea/controllers/changeset.py
--- a/kallithea/controllers/changeset.py
+++ b/kallithea/controllers/changeset.py
@@ -115,7 +115,7 @@ def get_line_ctx(fid, GET):
ln_ctx = filter(lambda k: k.startswith('C'), GET.getall(fid))
else:
_ln_ctx = filter(lambda k: k.startswith('C'), GET)
- ln_ctx = GET.get(_ln_ctx[0]) if _ln_ctx else ln_ctx_global
+ ln_ctx = GET.get(_ln_ctx[0]) if _ln_ctx else ln_ctx_global
if ln_ctx:
ln_ctx = [ln_ctx]
@@ -207,7 +207,7 @@ class ChangesetController(BaseRepoContro
c.ignorews_url = _ignorews_url
c.context_url = _context_url
c.fulldiff = fulldiff = request.GET.get('fulldiff')
- #get ranges of revisions if preset
+ # get ranges of revisions if preset
rev_range = revision.split('...')[:2]
enable_comments = True
c.cs_repo = c.db_repo
@@ -300,7 +300,7 @@ class ChangesetController(BaseRepoContro
file_diff_data.append(('', None, None, None, diff, None))
c.changes[changeset.raw_id] = (cs1, cs2, file_diff_data)
- #sort comments in creation order
+ # sort comments in creation order
c.comments = [com for com_id, com in sorted(comments.items())]
# count inline comments
diff --git a/kallithea/controllers/compare.py b/kallithea/controllers/compare.py
--- a/kallithea/controllers/compare.py
+++ b/kallithea/controllers/compare.py
@@ -94,7 +94,7 @@ class CompareController(BaseRepoControll
other_changesets = []
elif alias == 'hg':
- #case two independent repos
+ # case two independent repos
if org_repo != other_repo:
hgrepo = unionrepo.unionrepository(other_repo.baseui,
other_repo.path,
@@ -102,7 +102,7 @@ class CompareController(BaseRepoControll
# all ancestors of other_rev will be in other_repo and
# rev numbers from hgrepo can be used in other_repo - org_rev ancestors cannot
- #no remote compare do it on the same repository
+ # no remote compare do it on the same repository
else:
hgrepo = other_repo._repo
diff --git a/kallithea/controllers/feed.py b/kallithea/controllers/feed.py
--- a/kallithea/controllers/feed.py
+++ b/kallithea/controllers/feed.py
@@ -83,7 +83,7 @@ class FeedController(BaseRepoController)
def __get_desc(self, cs):
desc_msg = [(_('%s committed on %s')
% (h.person(cs.author), h.fmt_date(cs.date))) + '
']
- #branches, tags, bookmarks
+ # branches, tags, bookmarks
if cs.branch:
desc_msg.append('branch: %s
' % cs.branch)
for book in cs.bookmarks:
diff --git a/kallithea/controllers/files.py b/kallithea/controllers/files.py
--- a/kallithea/controllers/files.py
+++ b/kallithea/controllers/files.py
@@ -166,7 +166,7 @@ class FilesController(BaseRepoController
if c.file.is_file():
c.load_full_history = False
- #determine if we're on branch head
+ # determine if we're on branch head
_branches = c.db_repo_scm_instance.branches
c.on_branch_head = revision in _branches.keys() + _branches.values()
_hist = []
@@ -460,7 +460,7 @@ class FilesController(BaseRepoController
h.flash(_('No filename'), category='warning')
raise HTTPFound(location=url('changeset_home', repo_name=c.repo_name,
revision='tip'))
- #strip all crap out of file, just leave the basename
+ # strip all crap out of file, just leave the basename
filename = os.path.basename(filename)
node_path = posixpath.join(location, filename)
author = request.authuser.full_contact
@@ -599,8 +599,8 @@ class FilesController(BaseRepoController
c.changes = OrderedDict()
c.changes[diff2] = []
- #special case if we want a show rev only, it's impl here
- #to reduce JS and callbacks
+ # special case if we want a show rev only, it's impl here
+ # to reduce JS and callbacks
if request.GET.get('show_rev'):
if str2bool(request.GET.get('annotate', 'False')):
@@ -748,7 +748,7 @@ class FilesController(BaseRepoController
try:
changesets = tip_cs.get_file_history(f_path)
except (NodeDoesNotExistError, ChangesetError):
- #this node is not present at tip !
+ # this node is not present at tip !
changesets = cs.get_file_history(f_path)
hist_l = []
diff --git a/kallithea/controllers/home.py b/kallithea/controllers/home.py
--- a/kallithea/controllers/home.py
+++ b/kallithea/controllers/home.py
@@ -57,7 +57,7 @@ class HomeController(BaseController):
repos_data = RepoModel().get_repos_as_dict(repos_list=repos_list,
admin=False, short_name=True)
- #data used to render the grid
+ # data used to render the grid
c.data = repos_data
return render('/index.html')
@@ -65,7 +65,7 @@ class HomeController(BaseController):
@LoginRequired()
@jsonify
def repo_switcher_data(self):
- #wrapper for conditional cache
+ # wrapper for conditional cache
def _c():
log.debug('generating switcher repo/groups list')
all_repos = Repository.query(sorted=True).all()
diff --git a/kallithea/controllers/journal.py b/kallithea/controllers/journal.py
--- a/kallithea/controllers/journal.py
+++ b/kallithea/controllers/journal.py
@@ -69,7 +69,7 @@ class JournalController(BaseController):
groups = []
for k, g in groupby(journal, lambda x: x.action_as_day):
user_group = []
- #groupby username if it's a present value, else fallback to journal username
+ # groupby username if it's a present value, else fallback to journal username
for _unused, g2 in groupby(list(g), lambda x: x.user.username if x.user else x.username):
l = list(g2)
user_group.append((l[0].user, l))
@@ -97,7 +97,7 @@ class JournalController(BaseController):
journal = UserLog.query() \
.options(joinedload(UserLog.user)) \
.options(joinedload(UserLog.repository))
- #filter
+ # filter
journal = _journal_filter(journal, c.search_term)
journal = journal.filter(filtering_criterion) \
.order_by(UserLog.action_date.desc())
@@ -125,7 +125,7 @@ class JournalController(BaseController):
for entry in journal[:feed_nr]:
user = entry.user
if user is None:
- #fix deleted users
+ # fix deleted users
user = AttributeDict({'short_contact': entry.username,
'email': '',
'full_contact': ''})
@@ -167,7 +167,7 @@ class JournalController(BaseController):
for entry in journal[:feed_nr]:
user = entry.user
if user is None:
- #fix deleted users
+ # fix deleted users
user = AttributeDict({'short_contact': entry.username,
'email': '',
'full_contact': ''})
@@ -217,7 +217,7 @@ class JournalController(BaseController):
repos_data = RepoModel().get_repos_as_dict(repos_list=repos_list,
admin=True)
- #data used to render the grid
+ # data used to render the grid
c.data = repos_data
return render('journal/journal.html')
diff --git a/kallithea/controllers/pullrequests.py b/kallithea/controllers/pullrequests.py
--- a/kallithea/controllers/pullrequests.py
+++ b/kallithea/controllers/pullrequests.py
@@ -391,7 +391,7 @@ class PullrequestsController(BaseRepoCon
if pull_request.is_closed():
raise HTTPForbidden()
assert pull_request.other_repo.repo_name == repo_name
- #only owner or admin can update it
+ # only owner or admin can update it
owner = pull_request.owner_id == request.authuser.user_id
repo_admin = h.HasRepoPermissionLevel('admin')(c.repo_name)
if not (h.HasPermissionAny('hg.admin')() or repo_admin or owner):
@@ -446,7 +446,7 @@ class PullrequestsController(BaseRepoCon
@jsonify
def delete(self, repo_name, pull_request_id):
pull_request = PullRequest.get_or_404(pull_request_id)
- #only owner can delete it !
+ # only owner can delete it !
if pull_request.owner_id == request.authuser.user_id:
PullRequestModel().delete(pull_request)
Session().commit()
@@ -596,7 +596,7 @@ class PullrequestsController(BaseRepoCon
ignore_whitespace=ignore_whitespace,
context=line_context)
except ChangesetDoesNotExistError:
- txtdiff = _("The diff can't be shown - the PR revisions could not be found.")
+ txtdiff = _("The diff can't be shown - the PR revisions could not be found.")
diff_processor = diffs.DiffProcessor(txtdiff or '', format='gitdiff',
diff_limit=diff_limit)
_parsed = diff_processor.prepare()
@@ -734,7 +734,7 @@ class PullrequestsController(BaseRepoCon
def delete_comment(self, repo_name, comment_id):
co = ChangesetComment.get(comment_id)
if co.pull_request.is_closed():
- #don't allow deleting comments on closed pull request
+ # don't allow deleting comments on closed pull request
raise HTTPForbidden()
owner = co.author_id == request.authuser.user_id
diff --git a/kallithea/controllers/root.py b/kallithea/controllers/root.py
--- a/kallithea/controllers/root.py
+++ b/kallithea/controllers/root.py
@@ -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
diff --git a/kallithea/lib/annotate.py b/kallithea/lib/annotate.py
--- a/kallithea/lib/annotate.py
+++ b/kallithea/lib/annotate.py
@@ -149,7 +149,7 @@ class AnnotateHtmlFormatter(HtmlFormatte
for i in range(fl, fl + lncount):
if i % st == 0:
if aln:
- lines.append('%*d' \
+ lines.append('%*d'
% (la, i, mw, i))
else:
lines.append('%*d' % (mw, i))
@@ -158,7 +158,7 @@ class AnnotateHtmlFormatter(HtmlFormatte
ls = '\n'.join(lines)
# annotate_changesets = [tup[1] for tup in self.filenode.annotate]
-## TODO: not sure what that fixes
+# # TODO: not sure what that fixes
# # If pygments cropped last lines break we need do that too
# ln_cs = len(annotate_changesets)
# ln_ = len(ls.splitlines())
diff --git a/kallithea/lib/auth.py b/kallithea/lib/auth.py
--- a/kallithea/lib/auth.py
+++ b/kallithea/lib/auth.py
@@ -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__)
@@ -121,7 +121,7 @@ def check_password(password, hashed):
return hashlib.sha256(password).hexdigest() == hashed
elif is_unix:
import bcrypt
- print (safe_str(password), safe_str(hashed))
+ print(safe_str(password), safe_str(hashed))
try:
return bcrypt.checkpw(safe_str(password), safe_str(hashed))
except ValueError as e:
@@ -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
@@ -409,7 +409,7 @@ def _cached_perms_data(user_id, user_is_
p = _choose_perm(p, cur_perm)
permissions[UK][g_k] = p
- #user explicit permission for user groups
+ # user explicit permission for user groups
user_user_groups_perms = Permission.get_default_user_group_perms(user_id)
for perm in user_user_groups_perms:
u_k = perm.UserUserGroupToPerm.user_group.users_group_name
@@ -437,7 +437,7 @@ def allowed_api_access(controller_name,
else:
msg = 'controller: %s is *NOT* in API whitelist' % (controller_name)
if api_key:
- #if we use API key and don't have access it's a warning
+ # if we use API key and don't have access it's a warning
log.warning(msg)
else:
log.debug(msg)
@@ -510,7 +510,7 @@ class AuthUser(object):
# If user cannot be found, try falling back to anonymous.
if not is_user_loaded:
- is_user_loaded = self._fill_data(self._default_user)
+ is_user_loaded = self._fill_data(self._default_user)
self.is_default_user = (self.user_id == self._default_user.user_id)
self.is_anonymous = not is_user_loaded or self.is_default_user
diff --git a/kallithea/lib/auth_modules/__init__.py b/kallithea/lib/auth_modules/__init__.py
--- a/kallithea/lib/auth_modules/__init__.py
+++ b/kallithea/lib/auth_modules/__init__.py
@@ -40,7 +40,7 @@ class LazyFormencode(object):
from inspect import isfunction
formencode_obj = self.formencode_obj
if isfunction(formencode_obj):
- #case we wrap validators into functions
+ # case we wrap validators into functions
formencode_obj = self.formencode_obj(*args, **kwargs)
return formencode_obj(*self.args, **self.kwargs)
@@ -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'
diff --git a/kallithea/lib/base.py b/kallithea/lib/base.py
--- a/kallithea/lib/base.py
+++ b/kallithea/lib/base.py
@@ -290,7 +290,7 @@ class BaseVCSController(object):
log.error(traceback.format_exc())
return None, webob.exc.HTTPInternalServerError()
- #check permissions for this repository
+ # check permissions for this repository
perm = self._check_permission(action, user, repo_name, ip_addr)
if not perm:
return None, webob.exc.HTTPForbidden()
@@ -522,7 +522,7 @@ class BaseController(TGController):
self._basic_security_checks()
- #set globals for auth user
+ # set globals for auth user
bearer_token = None
try:
diff --git a/kallithea/lib/caching_query.py b/kallithea/lib/caching_query.py
--- a/kallithea/lib/caching_query.py
+++ b/kallithea/lib/caching_query.py
@@ -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:
@@ -234,7 +234,7 @@ def _params_from_query(query):
v.append(value)
if query._criterion is not None:
- visitors.traverse(query._criterion, {}, {'bindparam':visit_bindparam})
+ visitors.traverse(query._criterion, {}, {'bindparam': visit_bindparam})
for f in query._from_obj:
- visitors.traverse(f, {}, {'bindparam':visit_bindparam})
+ visitors.traverse(f, {}, {'bindparam': visit_bindparam})
return v
diff --git a/kallithea/lib/celerylib/__init__.py b/kallithea/lib/celerylib/__init__.py
--- a/kallithea/lib/celerylib/__init__.py
+++ b/kallithea/lib/celerylib/__init__.py
@@ -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)
diff --git a/kallithea/lib/celerylib/tasks.py b/kallithea/lib/celerylib/tasks.py
--- a/kallithea/lib/celerylib/tasks.py
+++ b/kallithea/lib/celerylib/tasks.py
@@ -180,7 +180,7 @@ def get_commits_stats(repo_name, ts_min_
"schema": ["commits"],
}
- #gather all data by day
+ # gather all data by day
if k in commits_by_day_aggregate:
commits_by_day_aggregate[k] += 1
else:
@@ -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):
@@ -471,7 +472,7 @@ def create_repo_fork(form_data, cur_user
except Exception as e:
log.warning('Exception %s occurred when forking repository, '
'doing cleanup...' % e)
- #rollback things manually !
+ # rollback things manually !
repo = Repository.get_by_repo_name(repo_name_full)
if repo:
Repository.delete(repo.repo_id)
diff --git a/kallithea/lib/celerypylons/__init__.py b/kallithea/lib/celerypylons/__init__.py
--- a/kallithea/lib/celerypylons/__init__.py
+++ b/kallithea/lib/celerypylons/__init__.py
@@ -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()
diff --git a/kallithea/lib/compat.py b/kallithea/lib/compat.py
--- a/kallithea/lib/compat.py
+++ b/kallithea/lib/compat.py
@@ -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()
diff --git a/kallithea/lib/db_manage.py b/kallithea/lib/db_manage.py
--- a/kallithea/lib/db_manage.py
+++ b/kallithea/lib/db_manage.py
@@ -84,7 +84,7 @@ class DbManage(object):
if SESSION:
self.sa = SESSION
else:
- #init new sessions
+ # init new sessions
engine = create_engine(self.dburi)
init_model(engine)
self.sa = Session()
@@ -205,7 +205,7 @@ class DbManage(object):
if password is None:
password = get_password()
if not password:
- #second try
+ # second try
password = get_password()
if not password:
sys.exit()
@@ -234,7 +234,7 @@ class DbManage(object):
Creates ui settings, fills out hooks
"""
- #HOOKS
+ # HOOKS
hooks1_key = Ui.HOOK_UPDATE
hooks1_ = Ui.query() \
.filter(Ui.ui_key == hooks1_key).scalar()
diff --git a/kallithea/lib/dbmigrate/__init__.py b/kallithea/lib/dbmigrate/__init__.py
--- a/kallithea/lib/dbmigrate/__init__.py
+++ b/kallithea/lib/dbmigrate/__init__.py
@@ -1,5 +1,6 @@
from gearbox.command import Command
+
class UpgradeDb(Command):
'''(removed)'''
diff --git a/kallithea/lib/diffs.py b/kallithea/lib/diffs.py
--- a/kallithea/lib/diffs.py
+++ b/kallithea/lib/diffs.py
@@ -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
@@ -375,7 +375,7 @@ class DiffProcessor(object):
def _clean_line(self, line, command):
if command in ['+', '-', ' ']:
- #only modify the line if it's actually a diff thing
+ # only modify the line if it's actually a diff thing
line = line[1:]
return line
@@ -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)
diff --git a/kallithea/lib/ext_json.py b/kallithea/lib/ext_json.py
--- a/kallithea/lib/ext_json.py
+++ b/kallithea/lib/ext_json.py
@@ -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
diff --git a/kallithea/lib/graphmod.py b/kallithea/lib/graphmod.py
--- a/kallithea/lib/graphmod.py
+++ b/kallithea/lib/graphmod.py
@@ -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').
diff --git a/kallithea/lib/helpers.py b/kallithea/lib/helpers.py
--- a/kallithea/lib/helpers.py
+++ b/kallithea/lib/helpers.py
@@ -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|)')
+
def _markup_whitespace(m):
groups = m.groups()
if groups[0]:
@@ -279,9 +285,11 @@ def _markup_whitespace(m):
if groups[1]:
return ' '
+
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()
#==============================================================================
@@ -438,7 +448,7 @@ flash = Flash()
from kallithea.lib.vcs.utils import author_name, author_email
from kallithea.lib.utils2 import credentials_filter, age as _age
-age = lambda x, y=False: _age(x, y)
+age = lambda x, y=False: _age(x, y)
capitalize = lambda x: x.capitalize()
email = author_email
short_id = lambda x: x[:12]
@@ -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"""
@@ -540,7 +552,7 @@ def person_by_id(id_, show_attr="usernam
# attr to return from fetched user
person_getter = lambda usr: getattr(usr, show_attr)
- #maybe it's an ID ?
+ # maybe it's an ID ?
if str(id_).isdigit() or isinstance(id_, int):
id_ = int(id_)
user = User.get(id_)
@@ -614,7 +626,7 @@ def action_parser(user_log, feed=False,
if parse_cs:
return link_to(lbl, url_, title=title_, **{'data-toggle': 'tooltip'})
return link_to(lbl, url_, class_='lazy-cs' if lazy_cs else '',
- **{'data-raw_id':rev.raw_id, 'data-repo_name':repo_name})
+ **{'data-raw_id': rev.raw_id, 'data-repo_name': repo_name})
def _get_op(rev_txt):
_op = None
@@ -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
@@ -931,7 +945,7 @@ def fancy_file_stats(stats):
width = 100
if stats['binary']:
- #binary mode
+ # binary mode
lbl = ''
bin_op = 1
@@ -951,7 +965,7 @@ def fancy_file_stats(stats):
lbl += _('rename')
bin_op = RENAMED_FILENODE
- #chmod can go with other operations
+ # chmod can go with other operations
if CHMOD_FILENODE in stats['ops']:
_org_lbl = _('chmod')
lbl += _org_lbl if lbl.endswith('+') else '+%s' % _org_lbl
@@ -970,7 +984,7 @@ def fancy_file_stats(stats):
p_sum = a_p + d_p
if p_sum > width:
- #adjust the percentage to be == 100% since we adjusted to 9
+ # adjust the percentage to be == 100% since we adjusted to 9
if a_p > d_p:
a_p = a_p - (p_sum - width)
else:
@@ -1013,7 +1027,6 @@ def fancy_file_stats(stats):
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)
diff --git a/kallithea/lib/hooks.py b/kallithea/lib/hooks.py
--- a/kallithea/lib/hooks.py
+++ b/kallithea/lib/hooks.py
@@ -98,7 +98,7 @@ def pre_push(ui, repo, **kwargs):
# on that proper return code is server to client
_http_ret = HTTPLockedRC(ex.repository, locked_by)
if str(_http_ret.code).startswith('2'):
- #2xx Codes don't raise exceptions
+ # 2xx Codes don't raise exceptions
ui.status(safe_str(_http_ret.title))
else:
raise _http_ret
@@ -113,7 +113,7 @@ def pre_pull(ui, repo, **kwargs):
# on that proper return code is server to client
_http_ret = HTTPLockedRC(ex.repository, locked_by)
if str(_http_ret.code).startswith('2'):
- #2xx Codes don't raise exceptions
+ # 2xx Codes don't raise exceptions
ui.status(safe_str(_http_ret.title))
else:
raise _http_ret
@@ -148,7 +148,7 @@ def log_pull_action(ui, repo, **kwargs):
locked_by = User.get(ex.locked_by[0]).username
_http_ret = HTTPLockedRC(ex.repository, locked_by)
if str(_http_ret.code).startswith('2'):
- #2xx Codes don't raise exceptions
+ # 2xx Codes don't raise exceptions
ui.status(safe_str(_http_ret.title))
return 0
@@ -203,7 +203,7 @@ def log_push_action(ui, repo, **kwargs):
locked_by = User.get(ex.locked_by[0]).username
_http_ret = HTTPLockedRC(ex.repository, locked_by)
if str(_http_ret.code).startswith('2'):
- #2xx Codes don't raise exceptions
+ # 2xx Codes don't raise exceptions
ui.status(safe_str(_http_ret.title))
return 0
@@ -446,7 +446,7 @@ def handle_git_receive(repo_path, revs,
repo._repo.refs.set_symbolic_ref('HEAD',
'refs/heads/%s' % push_ref['name'])
- cmd = ['for-each-ref', '--format=%(refname)','refs/heads/*']
+ cmd = ['for-each-ref', '--format=%(refname)', 'refs/heads/*']
heads = repo.run_git_command(cmd)[0]
cmd = ['log', push_ref['new_rev'],
'--reverse', '--pretty=format:%H', '--not']
@@ -456,7 +456,7 @@ def handle_git_receive(repo_path, revs,
git_revs += repo.run_git_command(cmd)[0].splitlines()
elif push_ref['new_rev'] == EmptyChangeset().raw_id:
- #delete branch case
+ # delete branch case
git_revs += ['delete_branch=>%s' % push_ref['name']]
else:
cmd = ['log', '%(old_rev)s..%(new_rev)s' % push_ref,
diff --git a/kallithea/lib/indexers/__init__.py b/kallithea/lib/indexers/__init__.py
--- a/kallithea/lib/indexers/__init__.py
+++ b/kallithea/lib/indexers/__init__.py
@@ -50,7 +50,7 @@ ANALYZER = RegexTokenizer(expression=r"\
# - avoid removing "stop words" from text
# - search case-insensitively
#
-EMAILADDRANALYZER = RegexTokenizer() | LowercaseFilter()
+EMAILADDRANALYZER = RegexTokenizer() | LowercaseFilter()
# CUSTOM ANALYZER raw-string + lowercase filter
#
@@ -77,7 +77,7 @@ IDANALYZER = IDTokenizer()
#
PATHANALYZER = RegexTokenizer() | LowercaseFilter()
-#INDEX SCHEMA DEFINITION
+# INDEX SCHEMA DEFINITION
SCHEMA = Schema(
fileid=ID(unique=True),
owner=TEXT(analyzer=EMAILADDRANALYZER),
diff --git a/kallithea/lib/indexers/daemon.py b/kallithea/lib/indexers/daemon.py
--- a/kallithea/lib/indexers/daemon.py
+++ b/kallithea/lib/indexers/daemon.py
@@ -77,9 +77,9 @@ class WhooshIndexingDaemon(object):
self.repo_paths = ScmModel().repo_scan(self.repo_location)
- #filter repo list
+ # filter repo list
if repo_list:
- #Fix non-ascii repo names to unicode
+ # Fix non-ascii repo names to unicode
repo_list = map(safe_unicode, repo_list)
self.filtered_repo_paths = {}
for repo_name, repo in self.repo_paths.items():
@@ -88,7 +88,7 @@ class WhooshIndexingDaemon(object):
self.repo_paths = self.filtered_repo_paths
- #filter update repo list
+ # filter update repo list
self.filtered_repo_update_paths = {}
if repo_update_list:
self.filtered_repo_update_paths = {}
diff --git a/kallithea/lib/ipaddr.py b/kallithea/lib/ipaddr.py
--- a/kallithea/lib/ipaddr.py
+++ b/kallithea/lib/ipaddr.py
@@ -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.
diff --git a/kallithea/lib/markup_renderer.py b/kallithea/lib/markup_renderer.py
--- a/kallithea/lib/markup_renderer.py
+++ b/kallithea/lib/markup_renderer.py
@@ -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)
diff --git a/kallithea/lib/middleware/pygrack.py b/kallithea/lib/middleware/pygrack.py
--- a/kallithea/lib/middleware/pygrack.py
+++ b/kallithea/lib/middleware/pygrack.py
@@ -72,7 +72,7 @@ class GitRepository(object):
def __init__(self, repo_name, content_path, extras):
files = set([f.lower() for f in os.listdir(content_path)])
- if not (self.git_folder_signature.intersection(files)
+ if not (self.git_folder_signature.intersection(files)
== self.git_folder_signature):
raise OSError('%s missing git signature' % content_path)
self.content_path = content_path
diff --git a/kallithea/lib/middleware/sessionmiddleware.py b/kallithea/lib/middleware/sessionmiddleware.py
--- a/kallithea/lib/middleware/sessionmiddleware.py
+++ b/kallithea/lib/middleware/sessionmiddleware.py
@@ -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):
"""
diff --git a/kallithea/lib/middleware/simplehg.py b/kallithea/lib/middleware/simplehg.py
--- a/kallithea/lib/middleware/simplehg.py
+++ b/kallithea/lib/middleware/simplehg.py
@@ -62,6 +62,7 @@ def is_mercurial(environ):
)
return ishg_path
+
class SimpleHg(BaseVCSController):
def _handle_request(self, environ, start_response):
@@ -229,7 +230,7 @@ class SimpleHg(BaseVCSController):
repoui = make_ui('file', hgrc)
if repoui:
- #overwrite our ui instance with the section from hgrc file
+ # overwrite our ui instance with the section from hgrc file
for section in ui_sections:
for k, v in repoui.configitems(section):
baseui.setconfig(section, k, v)
diff --git a/kallithea/lib/page.py b/kallithea/lib/page.py
--- a/kallithea/lib/page.py
+++ b/kallithea/lib/page.py
@@ -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
diff --git a/kallithea/lib/paster_commands/cleanup.py b/kallithea/lib/paster_commands/cleanup.py
--- a/kallithea/lib/paster_commands/cleanup.py
+++ b/kallithea/lib/paster_commands/cleanup.py
@@ -84,7 +84,7 @@ class Command(BasePasterCommand):
if dirs:
print 'Scanning: %s' % dn_
- #filter older than (if present)!
+ # filter older than (if present)!
now = datetime.datetime.now()
older_than = args.older_than
if older_than:
diff --git a/kallithea/lib/paster_commands/install_iis.py b/kallithea/lib/paster_commands/install_iis.py
--- a/kallithea/lib/paster_commands/install_iis.py
+++ b/kallithea/lib/paster_commands/install_iis.py
@@ -61,6 +61,7 @@ if __name__=='__main__':
HandleCommandLine(params)
'''
+
class Command(BasePasterCommand):
'''Kallithea: Install into IIS using isapi-wsgi'''
diff --git a/kallithea/lib/paster_commands/make_config.py b/kallithea/lib/paster_commands/make_config.py
--- a/kallithea/lib/paster_commands/make_config.py
+++ b/kallithea/lib/paster_commands/make_config.py
@@ -118,7 +118,7 @@ def _run(args):
tmpl_stored_args.update(kwargs)
if args.show_defaults:
- for k,v in tmpl_stored_args.iteritems():
+ for k, v in tmpl_stored_args.iteritems():
print '%s=%s' % (k, v)
sys.exit(0)
diff --git a/kallithea/lib/pidlock.py b/kallithea/lib/pidlock.py
--- a/kallithea/lib/pidlock.py
+++ b/kallithea/lib/pidlock.py
@@ -42,7 +42,7 @@ class DaemonLock(object):
self.desc = desc
self.debug = debug
self.held = False
- #run the lock automatically !
+ # run the lock automatically!
self.lock()
self._finalize = Finalize(self, DaemonLock._on_finalize,
args=(self, debug), exitpriority=10)
diff --git a/kallithea/lib/rcmail/response.py b/kallithea/lib/rcmail/response.py
--- a/kallithea/lib/rcmail/response.py
+++ b/kallithea/lib/rcmail/response.py
@@ -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):
"""
diff --git a/kallithea/lib/rcmail/utils.py b/kallithea/lib/rcmail/utils.py
--- a/kallithea/lib/rcmail/utils.py
+++ b/kallithea/lib/rcmail/utils.py
@@ -16,4 +16,5 @@ class CachedDnsName(object):
self._fqdn = socket.getfqdn()
return self._fqdn
+
DNS_NAME = CachedDnsName()
diff --git a/kallithea/lib/utils.py b/kallithea/lib/utils.py
--- a/kallithea/lib/utils.py
+++ b/kallithea/lib/utils.py
@@ -214,7 +214,7 @@ def get_filesystem_repos(path):
if REMOVED_REPO_PAT.match(subdir):
continue
- #skip . dirs TODO: rly? then we should prevent creating them ...
+ # skip . dirs TODO: rly? then we should prevent creating them ...
if subdir.startswith('.'):
continue
@@ -303,7 +303,7 @@ def is_valid_repo_group(repo_group_name,
return False
-#propagated from mercurial documentation
+# propagated from mercurial documentation
ui_sections = ['alias', 'auth',
'decode/encode', 'defaults',
'diff', 'email',
@@ -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')
@@ -556,13 +556,13 @@ def load_rcextensions(root_path):
# Additional mappings that are not present in the pygments lexers
conf.LANGUAGES_EXTENSIONS_MAP.update(getattr(EXT, 'EXTRA_MAPPINGS', {}))
- #OVERRIDE OUR EXTENSIONS FROM RC-EXTENSIONS (if present)
+ # OVERRIDE OUR EXTENSIONS FROM RC-EXTENSIONS (if present)
if getattr(EXT, 'INDEX_EXTENSIONS', []):
log.debug('settings custom INDEX_EXTENSIONS')
conf.INDEX_EXTENSIONS = getattr(EXT, 'INDEX_EXTENSIONS', [])
- #ADDITIONAL MAPPINGS
+ # ADDITIONAL MAPPINGS
log.debug('adding extra into INDEX_EXTENSIONS')
conf.INDEX_EXTENSIONS.extend(getattr(EXT, 'EXTRA_INDEX_EXTENSIONS', []))
diff --git a/kallithea/lib/utils2.py b/kallithea/lib/utils2.py
--- a/kallithea/lib/utils2.py
+++ b/kallithea/lib/utils2.py
@@ -297,7 +297,7 @@ def engine_from_config(configuration, pr
return ''.join([COLOR_SEQ % COLOR_SQL, sql, normal])
if configuration['debug']:
- #attach events only for debug configuration
+ # attach events only for debug configuration
def before_cursor_execute(conn, cursor, statement,
parameters, context, executemany):
@@ -458,7 +458,7 @@ def credentials_filter(uri):
"""
uri = uri_filter(uri)
- #check if we have port
+ # check if we have port
if len(uri) > 2 and uri[2]:
uri[2] = ':' + uri[2]
@@ -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,7 +651,8 @@ class OptionalAttr(object):
def __call__(self):
return self
-#alias
+
+# 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('_')
diff --git a/kallithea/lib/vcs/backends/base.py b/kallithea/lib/vcs/backends/base.py
--- a/kallithea/lib/vcs/backends/base.py
+++ b/kallithea/lib/vcs/backends/base.py
@@ -700,6 +700,7 @@ class BaseChangeset(object):
def phase(self):
return ''
+
class BaseWorkdir(object):
"""
Working directory representation of single repository.
diff --git a/kallithea/lib/vcs/backends/git/repository.py b/kallithea/lib/vcs/backends/git/repository.py
--- a/kallithea/lib/vcs/backends/git/repository.py
+++ b/kallithea/lib/vcs/backends/git/repository.py
@@ -118,7 +118,7 @@ class GitRepository(BaseRepository):
_copts = ['-c', 'core.quotepath=false', ]
safe_call = False
if '_safe' in opts:
- #no exc on failure
+ # no exc on failure
del opts['_safe']
safe_call = True
@@ -189,7 +189,7 @@ class GitRepository(BaseRepository):
test_uri = test_uri.rstrip('/') + '/info/refs'
if authinfo:
- #create a password manager
+ # create a password manager
passmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
passmgr.add_password(*authinfo)
@@ -262,7 +262,7 @@ class GitRepository(BaseRepository):
return so.splitlines()
def _get_all_revisions2(self):
- #alternate implementation using dulwich
+ # alternate implementation using dulwich
includes = [x[1][0] for x in self._parsed_refs.iteritems()
if x[1][1] != 'T']
return [c.commit.id for c in self._repo.get_walker(include=includes)]
@@ -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
diff --git a/kallithea/lib/vcs/backends/hg/changeset.py b/kallithea/lib/vcs/backends/hg/changeset.py
--- a/kallithea/lib/vcs/backends/hg/changeset.py
+++ b/kallithea/lib/vcs/backends/hg/changeset.py
@@ -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.
@@ -37,7 +38,7 @@ class MercurialChangeset(BaseChangeset):
@LazyProperty
def branch(self):
- return safe_unicode(self._ctx.branch())
+ return safe_unicode(self._ctx.branch())
@LazyProperty
def closesbranch(self):
@@ -411,7 +412,7 @@ class MercurialChangeset(BaseChangeset):
"""
Returns list of modified ``FileNode`` objects.
"""
- return ChangedFileNodesGenerator([n for n in self.status[0]], self)
+ return ChangedFileNodesGenerator([n for n in self.status[0]], self)
@property
def removed(self):
diff --git a/kallithea/lib/vcs/backends/hg/repository.py b/kallithea/lib/vcs/backends/hg/repository.py
--- a/kallithea/lib/vcs/backends/hg/repository.py
+++ b/kallithea/lib/vcs/backends/hg/repository.py
@@ -300,7 +300,7 @@ class MercurialRepository(BaseRepository
cleaned_uri = str(url_obj)
if authinfo:
- #create a password manager
+ # create a password manager
passmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
passmgr.add_password(*authinfo)
@@ -395,7 +395,7 @@ class MercurialRepository(BaseRepository
try:
return time.mktime(self.get_changeset().date.timetuple())
except RepositoryError:
- #fallback to filesystem
+ # fallback to filesystem
cl_path = os.path.join(self.path, '.hg', "00changelog.i")
st_path = os.path.join(self.path, '.hg', "store")
if os.path.exists(cl_path):
@@ -529,7 +529,7 @@ class MercurialRepository(BaseRepository
raise BranchDoesNotExistError(msg)
if end_pos is not None:
end_pos += 1
- #filter branches
+ # filter branches
filter_ = []
if branch_name:
filter_.append('branch("%s")' % (branch_name))
diff --git a/kallithea/lib/vcs/nodes.py b/kallithea/lib/vcs/nodes.py
--- a/kallithea/lib/vcs/nodes.py
+++ b/kallithea/lib/vcs/nodes.py
@@ -328,7 +328,7 @@ class FileNode(Node):
mtype = 'text/plain'
encoding = None
- #try with pygments
+ # try with pygments
try:
from pygments import lexers
mt = lexers.get_lexer_for_filename(self.name).mimetypes
@@ -609,7 +609,7 @@ class SubModuleNode(Node):
def _extract_submodule_url(self):
if self.alias == 'git':
- #TODO: find a way to parse gits submodule file and extract the
+ # TODO: find a way to parse gits submodule file and extract the
# linking URL
return self.path
if self.alias == 'hg':
diff --git a/kallithea/lib/vcs/subprocessio.py b/kallithea/lib/vcs/subprocessio.py
--- a/kallithea/lib/vcs/subprocessio.py
+++ b/kallithea/lib/vcs/subprocessio.py
@@ -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')
diff --git a/kallithea/lib/vcs/utils/__init__.py b/kallithea/lib/vcs/utils/__init__.py
--- a/kallithea/lib/vcs/utils/__init__.py
+++ b/kallithea/lib/vcs/utils/__init__.py
@@ -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.
diff --git a/kallithea/lib/vcs/utils/annotate.py b/kallithea/lib/vcs/utils/annotate.py
--- a/kallithea/lib/vcs/utils/annotate.py
+++ b/kallithea/lib/vcs/utils/annotate.py
@@ -122,7 +122,7 @@ class AnnotateHtmlFormatter(HtmlFormatte
for i in range(fl, fl + lncount):
if i % st == 0:
if aln:
- lines.append('%*d' \
+ lines.append('%*d'
% (la, i, mw, i))
else:
lines.append('%*d' % (mw, i))
@@ -134,7 +134,7 @@ class AnnotateHtmlFormatter(HtmlFormatte
# If pygments cropped last lines break we need do that too
ln_cs = len(annotate_changesets)
ln_ = len(ls.splitlines())
- if ln_cs > ln_:
+ if ln_cs > ln_:
annotate_changesets = annotate_changesets[:ln_ - ln_cs]
annotate = ''.join((self.annotate_from_changeset(changeset)
for changeset in annotate_changesets))
diff --git a/kallithea/lib/vcs/utils/diffs.py b/kallithea/lib/vcs/utils/diffs.py
--- a/kallithea/lib/vcs/utils/diffs.py
+++ b/kallithea/lib/vcs/utils/diffs.py
@@ -160,7 +160,7 @@ class DiffProcessor(object):
l.extend(output[1].splitlines(1))
return map(line_decoder, l)
elif size == 1:
- return map(line_decoder, output[0].splitlines(1))
+ return map(line_decoder, output[0].splitlines(1))
elif size == 0:
return []
diff --git a/kallithea/lib/vcs/utils/hgcompat.py b/kallithea/lib/vcs/utils/hgcompat.py
--- a/kallithea/lib/vcs/utils/hgcompat.py
+++ b/kallithea/lib/vcs/utils/hgcompat.py
@@ -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
@@ -37,7 +37,8 @@ from mercurial.url import httpbasicauthh
import inspect
# Mercurial 3.1 503bb3af70fe
if inspect.getargspec(memfilectx.__init__).args[1] != 'repo':
- _org__init__=memfilectx.__init__
+ _org__init__ = memfilectx.__init__
+
def _memfilectx__init__(self, repo, *a, **b):
return _org__init__(self, *a, **b)
memfilectx.__init__ = _memfilectx__init__
diff --git a/kallithea/lib/vcs/utils/lazy.py b/kallithea/lib/vcs/utils/lazy.py
--- a/kallithea/lib/vcs/utils/lazy.py
+++ b/kallithea/lib/vcs/utils/lazy.py
@@ -9,6 +9,7 @@ class _Missing(object):
def __reduce__(self):
return '_missing'
+
_missing = _Missing()
diff --git a/kallithea/lib/vcs/utils/progressbar.py b/kallithea/lib/vcs/utils/progressbar.py
--- a/kallithea/lib/vcs/utils/progressbar.py
+++ b/kallithea/lib/vcs/utils/progressbar.py
@@ -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
diff --git a/kallithea/lib/vcs/utils/termcolors.py b/kallithea/lib/vcs/utils/termcolors.py
--- a/kallithea/lib/vcs/utils/termcolors.py
+++ b/kallithea/lib/vcs/utils/termcolors.py
@@ -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
diff --git a/kallithea/lib/verlib.py b/kallithea/lib/verlib.py
--- a/kallithea/lib/verlib.py
+++ b/kallithea/lib/verlib.py
@@ -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(\.post(?P\d+))?(\.dev(?P\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.
@@ -267,7 +272,7 @@ def suggest_normalized_version(s):
rs = rs[1:]
# Clean leading '0's on numbers.
- #TODO: unintended side-effect on, e.g., "2003.05.09"
+ # TODO: unintended side-effect on, e.g., "2003.05.09"
# PyPI stats: 77 (~2%) better
rs = re.sub(r"\b0+(\d+)(?!\d)", r"\1", rs)
@@ -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)
diff --git a/kallithea/model/changeset_status.py b/kallithea/model/changeset_status.py
--- a/kallithea/model/changeset_status.py
+++ b/kallithea/model/changeset_status.py
@@ -165,7 +165,7 @@ class ChangesetStatusModel(object):
revisions = pull_request.revisions
cur_statuses = q.all()
- #if statuses exists and last is associated with a closed pull request
+ # if statuses exists and last is associated with a closed pull request
# we need to check if we can allow this status change
if (dont_allow_on_closed_pull_request and cur_statuses
and getattr(cur_statuses[0].pull_request, 'status', '')
@@ -174,7 +174,7 @@ class ChangesetStatusModel(object):
'Changing status on closed pull request is not allowed'
)
- #update all current statuses with older version
+ # update all current statuses with older version
for st in cur_statuses:
st.version += 1
diff --git a/kallithea/model/comment.py b/kallithea/model/comment.py
--- a/kallithea/model/comment.py
+++ b/kallithea/model/comment.py
@@ -67,7 +67,7 @@ class ChangesetCommentsModel(object):
if line_no:
line = _('on line %s') % line_no
- #changeset
+ # changeset
if revision:
notification_type = Notification.TYPE_CHANGESET_COMMENT
cs = repo.scm_instance.get_changeset(revision)
@@ -91,7 +91,7 @@ class ChangesetCommentsModel(object):
# add changeset author if it's known locally
cs_author = User.get_from_cs_author(cs.author)
if not cs_author:
- #use repo owner if we cannot extract the author correctly
+ # use repo owner if we cannot extract the author correctly
# FIXME: just use committer name even if not a user
cs_author = repo.owner
recipients.append(cs_author)
@@ -112,7 +112,7 @@ class ChangesetCommentsModel(object):
'comment_username': author.username,
'threading': threading,
}
- #pull request
+ # pull request
elif pull_request:
notification_type = Notification.TYPE_PULL_REQUEST_COMMENT
desc = comment.pull_request.title
@@ -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},
@@ -139,7 +139,7 @@ class ChangesetCommentsModel(object):
recipients.append(pull_request.owner)
recipients += pull_request.get_reviewer_users()
- #set some variables for email notification
+ # set some variables for email notification
email_kwargs = {
'pr_title': pull_request.title,
'pr_title_short': h.shorter(pull_request.title, 50),
diff --git a/kallithea/model/db.py b/kallithea/model/db.py
--- a/kallithea/model/db.py
+++ b/kallithea/model/db.py
@@ -457,12 +457,11 @@ class User(Base, BaseDbModel):
user_created_notifications = relationship('Notification', cascade='all')
# comments created by this user
user_comments = relationship('ChangesetComment', cascade='all')
- #extra emails for this user
+ # extra emails for this user
user_emails = relationship('UserEmailMap', cascade='all')
- #extra API keys
+ # extra API keys
user_api_keys = relationship('UserApiKeys', cascade='all')
-
@hybrid_property
def email(self):
return self._email
@@ -478,12 +477,12 @@ class User(Base, BaseDbModel):
@property
def emails(self):
- other = UserEmailMap.query().filter(UserEmailMap.user==self).all()
+ other = UserEmailMap.query().filter(UserEmailMap.user == self).all()
return [self.email] + [x.email for x in other]
@property
def api_keys(self):
- other = UserApiKeys.query().filter(UserApiKeys.user==self).all()
+ other = UserApiKeys.query().filter(UserApiKeys.user == self).all()
return [self.api_key] + [x.api_key for x in other]
@property
@@ -615,7 +614,7 @@ class User(Base, BaseDbModel):
res = q.scalar()
if fallback and not res:
- #fallback to additional keys
+ # fallback to additional keys
_res = UserApiKeys.query().filter_by(api_key=api_key, is_expired=False).first()
if _res:
res = _res.user
@@ -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__ = (
@@ -1752,7 +1752,7 @@ class Permission(Base, BaseDbModel):
('hg.extern_activate.auto', _('Automatic activation of external account')),
]
- #definition of system default permissions for DEFAULT user
+ # definition of system default permissions for DEFAULT user
DEFAULT_USER_PERMISSIONS = [
'repository.read',
'group.read',
@@ -2051,9 +2051,9 @@ class Statistics(Base, BaseDbModel):
stat_id = Column(Integer(), primary_key=True)
repository_id = Column(Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=True)
stat_on_revision = Column(Integer(), nullable=False)
- commit_activity = Column(LargeBinary(1000000), nullable=False)#JSON data
- commit_activity_combined = Column(LargeBinary(), nullable=False)#JSON data
- languages = Column(LargeBinary(1000000), nullable=False)#JSON data
+ commit_activity = Column(LargeBinary(1000000), nullable=False) # JSON data
+ commit_activity_combined = Column(LargeBinary(), nullable=False) # JSON data
+ languages = Column(LargeBinary(1000000), nullable=False) # JSON data
repository = relationship('Repository', single_parent=True)
@@ -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__ = (
diff --git a/kallithea/model/forms.py b/kallithea/model/forms.py
--- a/kallithea/model/forms.py
+++ b/kallithea/model/forms.py
@@ -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
@@ -170,8 +173,8 @@ def RepoGroupForm(edit=False, old_data=N
group_copy_permissions = v.StringBoolean(if_missing=False)
if edit:
- #FIXME: do a special check that we cannot move a group to one of
- #its children
+ # FIXME: do a special check that we cannot move a group to one of
+ # its children
pass
parent_group_id = All(v.CanCreateGroup(can_create_in_root),
@@ -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
@@ -466,7 +473,7 @@ def AuthSettingsForm(current_active_modu
validator = sv["validator"]
if isinstance(validator, LazyFormencode):
validator = validator()
- #init all lazy validators from formencode.All
+ # init all lazy validators from formencode.All
if isinstance(validator, All):
init_validators = []
for validator in validator.validators:
diff --git a/kallithea/model/gist.py b/kallithea/model/gist.py
--- a/kallithea/model/gist.py
+++ b/kallithea/model/gist.py
@@ -114,7 +114,7 @@ class GistModel(object):
log.debug('set GIST expiration date to: %s',
time_to_datetime(gist_expires)
if gist_expires != -1 else 'forever')
- #create the Database version
+ # create the Database version
gist = Gist()
gist.gist_description = description
gist.gist_access_id = gist_id
@@ -139,7 +139,7 @@ class GistModel(object):
raise Exception('Filename cannot be inside a directory')
content = gist_mapping[filename]['content']
- #TODO: expand support for setting explicit lexers
+ # TODO: expand support for setting explicit lexers
# if lexer is None:
# try:
# guess_lexer = pygments.lexers.guess_lexer_for_filename
@@ -153,7 +153,7 @@ class GistModel(object):
message += 's: ' if len(processed_mapping) > 1 else ': '
message += ', '.join([x for x in processed_mapping])
- #fake Kallithea Repository object
+ # fake Kallithea Repository object
fake_repo = AttributeDict(dict(
repo_name=gist_repo_path,
scm_instance_no_cache=lambda: repo,
@@ -192,7 +192,7 @@ class GistModel(object):
else:
gist_expires = time.time() + (lifetime * 60) if lifetime != -1 else -1
- #calculate operation type based on given data
+ # calculate operation type based on given data
gist_mapping_op = {}
for k, v in gist_mapping.items():
# add, mod, del
@@ -215,7 +215,7 @@ class GistModel(object):
message += 's: ' if len(gist_mapping) > 1 else ': '
message += ', '.join([x for x in gist_mapping])
- #fake Kallithea Repository object
+ # fake Kallithea Repository object
fake_repo = AttributeDict(dict(
repo_name=gist_repo.path,
scm_instance_no_cache=lambda: gist_repo,
diff --git a/kallithea/model/meta.py b/kallithea/model/meta.py
--- a/kallithea/model/meta.py
+++ b/kallithea/model/meta.py
@@ -38,8 +38,8 @@ 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
-#.options(FromCache("sqlalchemy_cache_type", "cachekey"))
+# to use cache use this in query:
+# .options(FromCache("sqlalchemy_cache_type", "cachekey"))
# Define naming conventions for foreign keys, primary keys, indexes,
diff --git a/kallithea/model/notification.py b/kallithea/model/notification.py
--- a/kallithea/model/notification.py
+++ b/kallithea/model/notification.py
@@ -98,7 +98,7 @@ class NotificationModel(object):
if not with_email:
return notif
- #don't send email to person who created this comment
+ # don't send email to person who created this comment
rec_objs = set(recipients_objs).difference(set([created_by_obj]))
headers = {}
@@ -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),
@@ -232,7 +232,7 @@ class NotificationModel(object):
Creates a human readable description based on properties
of notification object
"""
- #alias
+ # alias
_n = notification
if show_age:
diff --git a/kallithea/model/permission.py b/kallithea/model/permission.py
--- a/kallithea/model/permission.py
+++ b/kallithea/model/permission.py
@@ -116,13 +116,13 @@ class PermissionModel(object):
.all()
for p in u2p:
Session().delete(p)
- #create fresh set of permissions
+ # create fresh set of permissions
for def_perm_key in ['default_repo_perm',
'default_group_perm',
'default_user_group_perm',
'default_repo_create',
'create_on_write', # special case for create repos on write access to group
- #'default_repo_group_create', #not implemented yet
+ #'default_repo_group_create', # not implemented yet
'default_user_group_create',
'default_fork',
'default_register',
@@ -130,7 +130,7 @@ class PermissionModel(object):
p = _make_new(perm_user, form_result[def_perm_key])
Session().add(p)
- #stage 3 update all default permissions for repos if checked
+ # stage 3 update all default permissions for repos if checked
if form_result['overwrite_default_repo']:
_def_name = form_result['default_repo_perm'].split('repository.')[-1]
_def = Permission.get_by_key('repository.' + _def_name)
@@ -139,7 +139,7 @@ class PermissionModel(object):
.filter(UserRepoToPerm.user == perm_user) \
.all():
- #don't reset PRIVATE repositories
+ # don't reset PRIVATE repositories
if not r2p.repository.private:
r2p.permission = _def
diff --git a/kallithea/model/pull_request.py b/kallithea/model/pull_request.py
--- a/kallithea/model/pull_request.py
+++ b/kallithea/model/pull_request.py
@@ -61,12 +61,12 @@ class PullRequestModel(object):
mention_recipients = set(mention_recipients) - reviewers
_assert_valid_reviewers(mention_recipients)
- #members
+ # members
for reviewer in reviewers:
prr = PullRequestReviewer(reviewer, pr)
Session().add(prr)
- #notification to reviewers
+ # notification to reviewers
pr_url = pr.url(canonical=True)
threading = ['%s-pr-%s@%s' % (pr.other_repo.repo_name,
pr.pull_request_id,
@@ -265,7 +265,7 @@ class CreatePullRequestAction(object):
# create a ref under refs/pull/ so that commits don't get garbage-collected
self.org_repo.scm_instance._repo["refs/pull/%d/head" % pr.pull_request_id] = safe_str(self.org_rev)
- #reset state to under-review
+ # reset state to under-review
from kallithea.model.changeset_status import ChangesetStatusModel
from kallithea.model.comment import ChangesetCommentsModel
comment = ChangesetCommentsModel().create(
diff --git a/kallithea/model/repo.py b/kallithea/model/repo.py
--- a/kallithea/model/repo.py
+++ b/kallithea/model/repo.py
@@ -317,13 +317,13 @@ class RepoModel(object):
if 'repo_name' in kwargs:
cur_repo.repo_name = cur_repo.get_new_name(kwargs['repo_name'])
- #if private flag is set, reset default permission to NONE
+ # if private flag is set, reset default permission to NONE
if kwargs.get('repo_private'):
EMPTY_PERM = 'repository.none'
RepoModel().grant_user_permission(
repo=cur_repo, user='default', perm=EMPTY_PERM
)
- #handle extra fields
+ # handle extra fields
for field in filter(lambda k: k.startswith(RepositoryField.PREFIX),
kwargs):
k = RepositoryField.un_prefix_key(field)
@@ -460,7 +460,7 @@ class RepoModel(object):
repo=repo, user=member, perm=perm
)
else:
- #check if we have permissions to alter this usergroup's access
+ # check if we have permissions to alter this usergroup's access
if not check_perms or HasUserGroupPermissionLevel('read')(member):
self.grant_user_group_permission(
repo=repo, group_name=member, perm=perm
@@ -472,7 +472,7 @@ class RepoModel(object):
repo=repo, user=member, perm=perm
)
else:
- #check if we have permissions to alter this usergroup's access
+ # check if we have permissions to alter this usergroup's access
if not check_perms or HasUserGroupPermissionLevel('read')(member):
self.grant_user_group_permission(
repo=repo, group_name=member, perm=perm
diff --git a/kallithea/model/repo_group.py b/kallithea/model/repo_group.py
--- a/kallithea/model/repo_group.py
+++ b/kallithea/model/repo_group.py
@@ -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),
@@ -254,7 +254,7 @@ class RepoGroupModel(object):
_set_perm_user(obj, user=member, perm=perm)
## set for user group
else:
- #check if we have permissions to alter this usergroup's access
+ # check if we have permissions to alter this usergroup's access
if not check_perms or HasUserGroupPermissionLevel('read')(member):
_set_perm_group(obj, users_group=member, perm=perm)
# set new permissions
@@ -262,7 +262,7 @@ class RepoGroupModel(object):
if member_type == 'user':
_set_perm_user(obj, user=member, perm=perm)
else:
- #check if we have permissions to alter this usergroup's access
+ # check if we have permissions to alter this usergroup's access
if not check_perms or HasUserGroupPermissionLevel('read')(member):
_set_perm_group(obj, users_group=member, perm=perm)
updates.append(obj)
@@ -301,7 +301,7 @@ class RepoGroupModel(object):
# if obj is a Repo fix it's name
# this can be potentially heavy operation
for obj in repo_group.recursive_groups_and_repos():
- #set the value from it's parent
+ # set the value from it's parent
obj.enable_locking = repo_group.enable_locking
if isinstance(obj, RepoGroup):
new_name = obj.get_new_name(obj.name)
diff --git a/kallithea/model/scm.py b/kallithea/model/scm.py
--- a/kallithea/model/scm.py
+++ b/kallithea/model/scm.py
@@ -600,7 +600,7 @@ class ScmModel(object):
imc.remove(filenode)
elif op == 'mod':
if filename != old_filename:
- #TODO: handle renames, needs vcs lib changes
+ # TODO: handle renames, needs vcs lib changes
imc.remove(filenode)
imc.add(FileNode(filename, content=content))
else:
@@ -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.
diff --git a/kallithea/model/user_group.py b/kallithea/model/user_group.py
--- a/kallithea/model/user_group.py
+++ b/kallithea/model/user_group.py
@@ -71,7 +71,7 @@ class UserGroupModel(object):
user_group=user_group, user=member, perm=perm
)
else:
- #check if we have permissions to alter this usergroup's access
+ # check if we have permissions to alter this usergroup's access
if HasUserGroupPermissionLevel('read')(member):
self.grant_user_group_permission(
target_user_group=user_group, user_group=member, perm=perm
@@ -83,7 +83,7 @@ class UserGroupModel(object):
user_group=user_group, user=member, perm=perm
)
else:
- #check if we have permissions to alter this usergroup's access
+ # check if we have permissions to alter this usergroup's access
if HasUserGroupPermissionLevel('read')(member):
self.grant_user_group_permission(
target_user_group=user_group, user_group=member, perm=perm
diff --git a/kallithea/model/validators.py b/kallithea/model/validators.py
--- a/kallithea/model/validators.py
+++ b/kallithea/model/validators.py
@@ -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'),
@@ -83,7 +84,7 @@ def ValidUsername(edit=False, old_data=N
if value in ['default', 'new_user']:
msg = self.message('system_invalid_username', state, username=value)
raise formencode.Invalid(msg, value, state)
- #check if user is unique
+ # check if user is unique
old_un = None
if edit:
old_un = User.get(old_data.get('user_id')).username
@@ -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'),
@@ -142,7 +144,7 @@ def ValidUserGroup(edit=False, old_data=
raise formencode.Invalid(msg, value, state,
error_dict=dict(users_group_name=msg)
)
- #check if group is unique
+ # check if group is unique
old_ugname = None
if edit:
old_id = old_data.get('users_group_id')
@@ -494,7 +496,7 @@ def CanWriteGroup(old_data=None):
}
def _to_python(self, value, state):
- #root location
+ # root location
if value == -1:
return None
return value
@@ -520,7 +522,7 @@ def CanWriteGroup(old_data=None):
# don't need to check permission if he didn't change the value of
# groups in form box
if value_changed or new:
- #parent group need to be existing
+ # parent group need to be existing
if gr and forbidden:
msg = self.message('permission_denied', state)
raise formencode.Invalid(msg, value, state,
@@ -544,7 +546,7 @@ def CanCreateGroup(can_create_in_root=Fa
}
def to_python(self, value, state):
- #root location
+ # root location
if value == -1:
return None
return value
@@ -554,7 +556,7 @@ def CanCreateGroup(can_create_in_root=Fa
gr_name = gr.group_name if gr is not None else None # None means ROOT location
if can_create_in_root and gr is None:
- #we can create in root, we're fine no validations required
+ # we can create in root, we're fine no validations required
return
forbidden_in_root = gr is None and not can_create_in_root
@@ -587,7 +589,7 @@ def ValidPerms(type_='repo'):
perms_new = OrderedSet()
# build a list of permission to update and new permission to create
- #CLEAN OUT ORG VALUE FROM NEW MEMBERS, and group them using
+ # CLEAN OUT ORG VALUE FROM NEW MEMBERS, and group them using
new_perms_group = defaultdict(dict)
for k, v in value.copy().iteritems():
if k.startswith('perm_new_member'):
@@ -768,11 +770,11 @@ def ValidIp():
v = v.strip()
net = ipaddr.IPNetwork(address=v)
if isinstance(net, ipaddr.IPv4Network):
- #if IPv4 doesn't end with a mask, add /32
+ # if IPv4 doesn't end with a mask, add /32
if '/' not in value:
v += '/32'
if isinstance(net, ipaddr.IPv6Network):
- #if IPv6 doesn't end with a mask, add /128
+ # if IPv6 doesn't end with a mask, add /128
if '/' not in value:
v += '/128'
return v
@@ -780,7 +782,7 @@ def ValidIp():
def validate_python(self, value, state):
try:
addr = value.strip()
- #this raises an ValueError if address is not IPv4 or IPv6
+ # this raises an ValueError if address is not IPv4 or IPv6
ipaddr.IPNetwork(address=addr)
except ValueError:
raise formencode.Invalid(self.message('badFormat', state),
diff --git a/kallithea/tests/api/api_base.py b/kallithea/tests/api/api_base.py
--- a/kallithea/tests/api/api_base.py
+++ b/kallithea/tests/api/api_base.py
@@ -2482,7 +2482,7 @@ class _BaseTestApi(object):
def test_api_get_changeset(self):
review = fixture.review_changeset(self.REPO, self.TEST_REVISION, "approved")
id_, params = _build_data(self.apikey, 'get_changeset',
- repoid=self.REPO, raw_id = self.TEST_REVISION)
+ repoid=self.REPO, raw_id=self.TEST_REVISION)
response = api_call(self, params)
result = json.loads(response.body)["result"]
assert result["raw_id"] == self.TEST_REVISION
@@ -2491,8 +2491,8 @@ class _BaseTestApi(object):
def test_api_get_changeset_with_reviews(self):
reviewobjs = fixture.review_changeset(self.REPO, self.TEST_REVISION, "approved")
id_, params = _build_data(self.apikey, 'get_changeset',
- repoid=self.REPO, raw_id = self.TEST_REVISION,
- with_reviews = True)
+ repoid=self.REPO, raw_id=self.TEST_REVISION,
+ with_reviews=True)
response = api_call(self, params)
result = json.loads(response.body)["result"]
assert result["raw_id"] == self.TEST_REVISION
@@ -2522,7 +2522,7 @@ class _BaseTestApi(object):
RepoModel().revoke_user_permission(repo=self.REPO, user=self.TEST_USER_LOGIN)
RepoModel().revoke_user_permission(repo=self.REPO, user="default")
id_, params = _build_data(self.apikey_regular, 'get_changeset',
- repoid=self.REPO, raw_id = self.TEST_REVISION)
+ repoid=self.REPO, raw_id=self.TEST_REVISION)
response = api_call(self, params)
expected = u'Access denied to repo %s' % self.REPO
self._compare_error(id_, expected, given=response.body)
diff --git a/kallithea/tests/base.py b/kallithea/tests/base.py
--- a/kallithea/tests/base.py
+++ b/kallithea/tests/base.py
@@ -54,7 +54,7 @@ testapp = None
# 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
@@ -106,7 +106,7 @@ TEST_HG_REPO_PULL = os.path.join(TESTS_T
GIT_REMOTE_REPO = os.path.join(TESTS_TMP_PATH, GIT_REPO)
HG_REMOTE_REPO = os.path.join(TESTS_TMP_PATH, HG_REPO)
-#skip ldap tests if LDAP lib is not installed
+# skip ldap tests if LDAP lib is not installed
ldap_lib_installed = False
try:
import ldap
@@ -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"""
diff --git a/kallithea/tests/conftest.py b/kallithea/tests/conftest.py
--- a/kallithea/tests/conftest.py
+++ b/kallithea/tests/conftest.py
@@ -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.
diff --git a/kallithea/tests/fixture.py b/kallithea/tests/fixture.py
--- a/kallithea/tests/fixture.py
+++ b/kallithea/tests/fixture.py
@@ -257,11 +257,11 @@ 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(
- description=form_data['description'],owner=form_data['owner'],
+ description=form_data['description'], owner=form_data['owner'],
gist_mapping=form_data['gist_mapping'], gist_type=form_data['gist_type'],
lifetime=form_data['lifetime']
)
@@ -376,7 +376,7 @@ def create_test_env(repos_test_path, con
idx_path = config['index_dir']
data_path = config['cache_dir']
- #clean index and data
+ # clean index and data
if idx_path and os.path.exists(idx_path):
log.debug('remove %s', idx_path)
shutil.rmtree(idx_path)
@@ -385,7 +385,7 @@ def create_test_env(repos_test_path, con
log.debug('remove %s', data_path)
shutil.rmtree(data_path)
- #CREATE DEFAULT TEST REPOS
+ # CREATE DEFAULT TEST REPOS
tar = tarfile.open(os.path.join(FIXTURES, 'vcs_test_hg.tar.gz'))
tar.extractall(os.path.join(TESTS_TMP_PATH, HG_REPO))
tar.close()
@@ -394,7 +394,7 @@ def create_test_env(repos_test_path, con
tar.extractall(os.path.join(TESTS_TMP_PATH, GIT_REPO))
tar.close()
- #LOAD VCS test stuff
+ # LOAD VCS test stuff
from kallithea.tests.vcs import setup_package
setup_package()
diff --git a/kallithea/tests/functional/test_admin_auth_settings.py b/kallithea/tests/functional/test_admin_auth_settings.py
--- a/kallithea/tests/functional/test_admin_auth_settings.py
+++ b/kallithea/tests/functional/test_admin_auth_settings.py
@@ -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',
diff --git a/kallithea/tests/functional/test_admin_gists.py b/kallithea/tests/functional/test_admin_gists.py
--- a/kallithea/tests/functional/test_admin_gists.py
+++ b/kallithea/tests/functional/test_admin_gists.py
@@ -50,7 +50,7 @@ class TestGistsController(TestController
response = self.app.get(url('gists', private=1))
# Test response...
- #and privates
+ # and privates
response.mustcontain('gist: %s' % gist.gist_access_id)
def test_create_missing_description(self):
diff --git a/kallithea/tests/functional/test_admin_notifications.py b/kallithea/tests/functional/test_admin_notifications.py
--- a/kallithea/tests/functional/test_admin_notifications.py
+++ b/kallithea/tests/functional/test_admin_notifications.py
@@ -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()
diff --git a/kallithea/tests/functional/test_admin_permissions.py b/kallithea/tests/functional/test_admin_permissions.py
--- a/kallithea/tests/functional/test_admin_permissions.py
+++ b/kallithea/tests/functional/test_admin_permissions.py
@@ -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'))
diff --git a/kallithea/tests/functional/test_admin_repo_groups.py b/kallithea/tests/functional/test_admin_repo_groups.py
--- a/kallithea/tests/functional/test_admin_repo_groups.py
+++ b/kallithea/tests/functional/test_admin_repo_groups.py
@@ -7,6 +7,7 @@ from kallithea.tests.fixture import Fixt
fixture = Fixture()
+
class TestRepoGroupsController(TestController):
def test_case_insensitivity(self):
diff --git a/kallithea/tests/functional/test_admin_repos.py b/kallithea/tests/functional/test_admin_repos.py
--- a/kallithea/tests/functional/test_admin_repos.py
+++ b/kallithea/tests/functional/test_admin_repos.py
@@ -305,7 +305,7 @@ class _BaseTestCase(TestController):
Session().commit()
pytest.fail('no repo %s in filesystem' % repo_name)
- #check if inherited permissiona are applied
+ # check if inherited permissiona are applied
inherited_perms = UserRepoToPerm.query() \
.filter(UserRepoToPerm.repository_id == new_repo_id).all()
assert len(inherited_perms) == 2
@@ -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
@@ -387,7 +385,7 @@ class _BaseTestCase(TestController):
response.follow()
- #check if repo was deleted from db
+ # check if repo was deleted from db
deleted_repo = Session().query(Repository) \
.filter(Repository.repo_name == repo_name).scalar()
@@ -437,7 +435,7 @@ class _BaseTestCase(TestController):
self.checkSessionFlash(response, 'Deleted repository %s' % (repo_name_unicode))
response.follow()
- #check if repo was deleted from db
+ # check if repo was deleted from db
deleted_repo = Session().query(Repository) \
.filter(Repository.repo_name == repo_name_unicode).scalar()
@@ -446,7 +444,7 @@ class _BaseTestCase(TestController):
assert os.path.isdir(os.path.join(Ui.get_by_key('paths', '/').ui_value, repo_name_unicode)) == False
def test_delete_repo_with_group(self):
- #TODO:
+ # TODO:
pass
def test_delete_browser_fakeout(self):
@@ -462,7 +460,7 @@ class _BaseTestCase(TestController):
def test_set_private_flag_sets_default_to_none(self):
self.log_user()
- #initially repository perm should be read
+ # initially repository perm should be read
perm = _get_permission_for_user(user='default', repo=self.REPO)
assert len(perm), 1
assert perm[0].permission.permission_name == 'repository.read'
@@ -478,7 +476,7 @@ class _BaseTestCase(TestController):
msg='Repository %s updated successfully' % (self.REPO))
assert Repository.get_by_repo_name(self.REPO).private == True
- #now the repo default permission should be None
+ # now the repo default permission should be None
perm = _get_permission_for_user(user='default', repo=self.REPO)
assert len(perm), 1
assert perm[0].permission.permission_name == 'repository.none'
@@ -493,12 +491,12 @@ class _BaseTestCase(TestController):
msg='Repository %s updated successfully' % (self.REPO))
assert Repository.get_by_repo_name(self.REPO).private == False
- #we turn off private now the repo default permission should stay None
+ # we turn off private now the repo default permission should stay None
perm = _get_permission_for_user(user='default', repo=self.REPO)
assert len(perm), 1
assert perm[0].permission.permission_name == 'repository.none'
- #update this permission back
+ # update this permission back
perm[0].permission = Permission.get_by_key('repository.read')
Session().commit()
diff --git a/kallithea/tests/functional/test_admin_user_groups.py b/kallithea/tests/functional/test_admin_user_groups.py
--- a/kallithea/tests/functional/test_admin_user_groups.py
+++ b/kallithea/tests/functional/test_admin_user_groups.py
@@ -42,7 +42,7 @@ class TestAdminUsersGroupsController(Tes
self.log_user()
users_group_name = TEST_USER_GROUP + 'another'
response = self.app.post(url('users_groups'),
- {'users_group_name':users_group_name,
+ {'users_group_name': users_group_name,
'user_group_description': u'DESC',
'active': True,
'_authentication_token': self.authentication_token()})
diff --git a/kallithea/tests/functional/test_admin_users.py b/kallithea/tests/functional/test_admin_users.py
--- a/kallithea/tests/functional/test_admin_users.py
+++ b/kallithea/tests/functional/test_admin_users.py
@@ -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'
@@ -159,14 +161,13 @@ class TestAdminUsersController(TestContr
if name == 'email':
params['emails'] = [attrs['email']]
if name == 'extern_type':
- #cannot update this via form, expected value is original one
+ # cannot update this via form, expected value is original one
params['extern_type'] = "internal"
if name == 'extern_name':
- #cannot update this via form, expected value is original one
+ # 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)
@@ -288,7 +289,7 @@ class TestAdminUsersController(TestContr
uid = user.user_id
try:
- #User should have None permission on creation repository
+ # User should have None permission on creation repository
assert UserModel().has_perm(user, perm_none) == False
assert UserModel().has_perm(user, perm_create) == False
@@ -299,7 +300,7 @@ class TestAdminUsersController(TestContr
perm_none = Permission.get_by_key('hg.create.none')
perm_create = Permission.get_by_key('hg.create.repository')
- #User should have None permission on creation repository
+ # User should have None permission on creation repository
assert UserModel().has_perm(uid, perm_none) == False
assert UserModel().has_perm(uid, perm_create) == True
finally:
@@ -318,7 +319,7 @@ class TestAdminUsersController(TestContr
uid = user.user_id
try:
- #User should have None permission on creation repository
+ # User should have None permission on creation repository
assert UserModel().has_perm(user, perm_none) == False
assert UserModel().has_perm(user, perm_create) == False
@@ -328,7 +329,7 @@ class TestAdminUsersController(TestContr
perm_none = Permission.get_by_key('hg.create.none')
perm_create = Permission.get_by_key('hg.create.repository')
- #User should have None permission on creation repository
+ # User should have None permission on creation repository
assert UserModel().has_perm(uid, perm_none) == True
assert UserModel().has_perm(uid, perm_create) == False
finally:
@@ -347,7 +348,7 @@ class TestAdminUsersController(TestContr
uid = user.user_id
try:
- #User should have None permission on creation repository
+ # User should have None permission on creation repository
assert UserModel().has_perm(user, perm_none) == False
assert UserModel().has_perm(user, perm_fork) == False
@@ -358,7 +359,7 @@ class TestAdminUsersController(TestContr
perm_none = Permission.get_by_key('hg.create.none')
perm_create = Permission.get_by_key('hg.create.repository')
- #User should have None permission on creation repository
+ # User should have None permission on creation repository
assert UserModel().has_perm(uid, perm_none) == False
assert UserModel().has_perm(uid, perm_create) == True
finally:
@@ -377,7 +378,7 @@ class TestAdminUsersController(TestContr
uid = user.user_id
try:
- #User should have None permission on creation repository
+ # User should have None permission on creation repository
assert UserModel().has_perm(user, perm_none) == False
assert UserModel().has_perm(user, perm_fork) == False
@@ -387,7 +388,7 @@ class TestAdminUsersController(TestContr
perm_none = Permission.get_by_key('hg.create.none')
perm_create = Permission.get_by_key('hg.create.repository')
- #User should have None permission on creation repository
+ # User should have None permission on creation repository
assert UserModel().has_perm(uid, perm_none) == True
assert UserModel().has_perm(uid, perm_create) == False
finally:
@@ -491,7 +492,7 @@ class TestAdminUsersController(TestContr
self.checkSessionFlash(response, 'API key successfully created')
response = response.follow()
- #now delete our key
+ # now delete our key
keys = UserApiKeys.query().filter(UserApiKeys.user_id == user_id).all()
assert 1 == len(keys)
diff --git a/kallithea/tests/functional/test_changelog.py b/kallithea/tests/functional/test_changelog.py
--- a/kallithea/tests/functional/test_changelog.py
+++ b/kallithea/tests/functional/test_changelog.py
@@ -15,7 +15,7 @@ class TestChangelogController(TestContro
"""name="7b22a518347bb9bc19679f6af07cd0a61bfe16e7" """
"""type="checkbox" value="1" />"""
)
- #rev 640: code garden
+ # rev 640: code garden
response.mustcontain(
"""r640:0a4e54a44604""" % HG_REPO
)
@@ -25,7 +25,7 @@ class TestChangelogController(TestContro
def test_index_pagination_hg(self):
self.log_user()
- #pagination
+ # pagination
self.app.get(url(controller='changelog', action='index',
repo_name=HG_REPO), {'page': 1})
self.app.get(url(controller='changelog', action='index',
@@ -81,7 +81,7 @@ class TestChangelogController(TestContro
def test_index_pagination_git(self):
self.log_user()
- #pagination
+ # pagination
self.app.get(url(controller='changelog', action='index',
repo_name=GIT_REPO), {'page': 1})
self.app.get(url(controller='changelog', action='index',
@@ -112,7 +112,7 @@ class TestChangelogController(TestContro
response = self.app.get(url(controller='changelog', action='index',
revision='tip', f_path='/vcs/exceptions.py',
repo_name=HG_REPO))
- #history commits messages
+ # history commits messages
response.mustcontain('Added exceptions module, this time for real')
response.mustcontain('Added not implemented hg backend test case')
response.mustcontain('Added BaseChangeset class')
@@ -123,7 +123,7 @@ class TestChangelogController(TestContro
response = self.app.get(url(controller='changelog', action='index',
revision='tip', f_path='/vcs/exceptions.py',
repo_name=GIT_REPO))
- #history commits messages
+ # history commits messages
response.mustcontain('Added exceptions module, this time for real')
response.mustcontain('Added not implemented hg backend test case')
response.mustcontain('Added BaseChangeset class')
diff --git a/kallithea/tests/functional/test_changeset_comments.py b/kallithea/tests/functional/test_changeset_comments.py
--- a/kallithea/tests/functional/test_changeset_comments.py
+++ b/kallithea/tests/functional/test_changeset_comments.py
@@ -62,7 +62,7 @@ class TestChangeSetCommentsController(Te
response = self.app.get(url(controller='changeset', action='index',
repo_name=HG_REPO, revision=rev))
- #test DB
+ # test DB
assert ChangesetComment.query().count() == 1
response.mustcontain(
'''