You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@allura.apache.org by jo...@apache.org on 2014/01/10 22:23:25 UTC
[29/36] PEP8 cleanup
http://git-wip-us.apache.org/repos/asf/incubator-allura/blob/c93733ac/Allura/allura/controllers/project.py
----------------------------------------------------------------------
diff --git a/Allura/allura/controllers/project.py b/Allura/allura/controllers/project.py
index b0e5b8b..cdbba4c 100644
--- a/Allura/allura/controllers/project.py
+++ b/Allura/allura/controllers/project.py
@@ -54,16 +54,20 @@ from .static import NewForgeController
log = logging.getLogger(__name__)
+
class W:
resize_editor = ffw.AutoResizeTextarea()
project_summary = plw.ProjectSummary()
- add_project = plugin.ProjectRegistrationProvider.get().add_project_widget(antispam=True)
+ add_project = plugin.ProjectRegistrationProvider.get().add_project_widget(
+ antispam=True)
page_list = ffw.PageList()
page_size = ffw.PageSize()
project_select = ffw.NeighborhoodProjectSelect
neighborhood_overview_form = ff.NeighborhoodOverviewForm()
+
class NeighborhoodController(object):
+
'''Manages a neighborhood of projects.
'''
@@ -71,7 +75,8 @@ class NeighborhoodController(object):
self.neighborhood = neighborhood
self.neighborhood_name = self.neighborhood.name
self.prefix = self.neighborhood.shortname_prefix
- self.browse = NeighborhoodProjectBrowseController(neighborhood=self.neighborhood)
+ self.browse = NeighborhoodProjectBrowseController(
+ neighborhood=self.neighborhood)
self._admin = NeighborhoodAdminController(self.neighborhood)
self._moderate = NeighborhoodModerateController(self.neighborhood)
self.import_project = ProjectImporterController(self.neighborhood)
@@ -84,17 +89,20 @@ class NeighborhoodController(object):
pname = unquote(pname)
provider = plugin.ProjectRegistrationProvider.get()
try:
- provider.shortname_validator.to_python(pname, check_allowed=False, neighborhood=self.neighborhood)
+ provider.shortname_validator.to_python(
+ pname, check_allowed=False, neighborhood=self.neighborhood)
except Invalid:
project = None
else:
- project = M.Project.query.get(shortname=self.prefix + pname, neighborhood_id=self.neighborhood._id)
+ project = M.Project.query.get(
+ shortname=self.prefix + pname, neighborhood_id=self.neighborhood._id)
if project is None and self.prefix == 'u/':
# create user-project if it is missing
user = M.User.query.get(username=pname, disabled=False)
if user:
project = self.neighborhood.register_project(
- plugin.AuthenticationProvider.get(request).user_project_shortname(user),
+ plugin.AuthenticationProvider.get(
+ request).user_project_shortname(user),
user=user, user_project=True)
if project is None:
# look for neighborhood tools matching the URL
@@ -141,10 +149,10 @@ class NeighborhoodController(object):
c.page_list = W.page_list
limit, page, start = g.handle_paging(limit, page)
pq = M.Project.query.find(dict(
- neighborhood_id=self.neighborhood._id,
- deleted=False,
- is_nbhd_project=False,
- ))
+ neighborhood_id=self.neighborhood._id,
+ deleted=False,
+ is_nbhd_project=False,
+ ))
if sort == 'alpha':
pq.sort('name')
else:
@@ -152,11 +160,13 @@ class NeighborhoodController(object):
count = pq.count()
nb_max_projects = self.neighborhood.get_max_projects()
projects = pq.skip(start).limit(int(limit)).all()
- categories = M.ProjectCategory.query.find({'parent_id':None}).sort('name').all()
+ categories = M.ProjectCategory.query.find(
+ {'parent_id': None}).sort('name').all()
c.custom_sidebar_menu = []
if h.has_access(self.neighborhood, 'register')() and (nb_max_projects is None or count < nb_max_projects):
c.custom_sidebar_menu += [
- SitemapEntry('Add a Project', self.neighborhood.url() + 'add_project', ui_icon=g.icons['plus']),
+ SitemapEntry('Add a Project', self.neighborhood.url()
+ + 'add_project', ui_icon=g.icons['plus']),
SitemapEntry('')
]
c.custom_sidebar_menu = c.custom_sidebar_menu + [
@@ -164,7 +174,8 @@ class NeighborhoodController(object):
]
return dict(neighborhood=self.neighborhood,
title="Welcome to " + self.neighborhood.name,
- text=g.markdown.cached_convert(self.neighborhood, 'homepage'),
+ text=g.markdown.cached_convert(
+ self.neighborhood, 'homepage'),
projects=projects,
sort=sort,
limit=limit, page=page, count=count)
@@ -175,7 +186,8 @@ class NeighborhoodController(object):
c.project = self.neighborhood.neighborhood_project
require_access(self.neighborhood, 'register')
c.add_project = W.add_project
- form_data.setdefault('tools', [u'Wiki',u'Git',u'Tickets',u'Discussion'])
+ form_data.setdefault(
+ 'tools', [u'Wiki', u'Git', u'Tickets', u'Discussion'])
form_data['neighborhood'] = self.neighborhood.name
return dict(neighborhood=self.neighborhood, form_data=form_data)
@@ -183,7 +195,7 @@ class NeighborhoodController(object):
def suggest_name(self, project_name=''):
provider = plugin.ProjectRegistrationProvider.get()
return dict(suggested_name=provider.suggest_name(project_name,
- self.neighborhood))
+ self.neighborhood))
@expose('json:')
@validate(W.add_project)
@@ -195,27 +207,33 @@ class NeighborhoodController(object):
@validate(W.add_project, error_handler=add_project)
@utils.AntiSpam.validate('Spambot protection engaged')
@require_post()
- def register(self, project_unixname=None, project_description=None, project_name=None, neighborhood=None,
- private_project=None, tools=None, **kw):
+ def register(
+ self, project_unixname=None, project_description=None, project_name=None, neighborhood=None,
+ private_project=None, tools=None, **kw):
require_access(self.neighborhood, 'register')
if private_project:
require_access(self.neighborhood, 'admin')
neighborhood = M.Neighborhood.query.get(name=neighborhood)
- project_description = h.really_unicode(project_description or '').encode('utf-8')
+ project_description = h.really_unicode(
+ project_description or '').encode('utf-8')
project_name = h.really_unicode(project_name or '').encode('utf-8')
- project_unixname = h.really_unicode(project_unixname or '').encode('utf-8').lower()
+ project_unixname = h.really_unicode(
+ project_unixname or '').encode('utf-8').lower()
try:
c.project = neighborhood.register_project(project_unixname,
- project_name=project_name, private_project=private_project)
+ project_name=project_name, private_project=private_project)
except exceptions.ProjectOverlimitError:
- flash("You have exceeded the maximum number of projects you are allowed to create", 'error')
+ flash(
+ "You have exceeded the maximum number of projects you are allowed to create", 'error')
redirect('add_project')
except exceptions.ProjectRatelimitError:
- flash("Project creation rate limit exceeded. Please try again later.", 'error')
+ flash(
+ "Project creation rate limit exceeded. Please try again later.", 'error')
redirect('add_project')
except Exception as e:
- log.error('error registering project: %s', project_unixname, exc_info=True)
+ log.error('error registering project: %s',
+ project_unixname, exc_info=True)
flash('Internal Error. Please try again later.', 'error')
redirect('add_project')
@@ -250,11 +268,13 @@ class NeighborhoodController(object):
class NeighborhoodProjectBrowseController(ProjectBrowseController):
+
def __init__(self, neighborhood=None, category_name=None, parent_category=None):
self.neighborhood = neighborhood
- super(NeighborhoodProjectBrowseController, self).__init__(category_name=category_name, parent_category=parent_category)
+ super(NeighborhoodProjectBrowseController, self).__init__(
+ category_name=category_name, parent_category=parent_category)
self.nav_stub = '%sbrowse/' % self.neighborhood.url()
- self.additional_filters = {'neighborhood_id':self.neighborhood._id}
+ self.additional_filters = {'neighborhood_id': self.neighborhood._id}
@expose()
def _lookup(self, category_name, *remainder):
@@ -268,7 +288,8 @@ class NeighborhoodProjectBrowseController(ProjectBrowseController):
c.project_summary = W.project_summary
c.page_list = W.page_list
limit, page, start = g.handle_paging(limit, page)
- projects, count = self._find_projects(sort=sort, limit=limit, start=start)
+ projects, count = self._find_projects(
+ sort=sort, limit=limit, start=start)
title = self._build_title()
c.custom_sidebar_menu = self._build_nav()
return dict(projects=projects,
@@ -278,7 +299,9 @@ class NeighborhoodProjectBrowseController(ProjectBrowseController):
sort=sort,
limit=limit, page=page, count=count)
+
class HostNeighborhoodController(WsgiDispatchController, NeighborhoodController):
+
'''Neighborhood controller with support for use as a root controller, for
instance, when using adobe.sourceforge.net (if this is allowed).
'''
@@ -288,16 +311,19 @@ class HostNeighborhoodController(WsgiDispatchController, NeighborhoodController)
nf = NewForgeController()
search = SearchController()
+
class ToolListController(object):
+
"""Renders a list of all tools of a given type in the current project."""
@expose('jinja:allura:templates/tool_list.html')
def _default(self, tool_name, *args, **kw):
tool_name = tool_name.lower()
entries = [e for e in c.project.sitemap()
- if e.tool_name and e.tool_name.lower() == tool_name]
+ if e.tool_name and e.tool_name.lower() == tool_name]
return dict(entries=entries, type=g.entry_points['tool'][tool_name].tool_label if entries else None)
+
class ProjectController(FeedController):
def __init__(self):
@@ -309,18 +335,20 @@ class ProjectController(FeedController):
def _nav(self):
menu = []
for s in c.project.grouped_navbar_entries():
- entry = dict(name=s.label, url=s.url, icon=s.ui_icon, tool_name=s.tool_name)
+ entry = dict(name=s.label, url=s.url,
+ icon=s.ui_icon, tool_name=s.tool_name)
if s.children:
entry['children'] = [dict(name=child.label, url=child.url, icon=child.ui_icon, tool_name=child.tool_name)
- for child in s.children]
+ for child in s.children]
menu.append(entry)
return dict(menu=menu)
@expose()
def _lookup(self, name, *remainder):
name = unquote(name)
- subproject = M.Project.query.get(shortname=c.project.shortname + '/' + name,
- neighborhood_id=c.project.neighborhood_id)
+ subproject = M.Project.query.get(
+ shortname=c.project.shortname + '/' + name,
+ neighborhood_id=c.project.neighborhood_id)
if subproject:
c.project = subproject
c.app = None
@@ -341,13 +369,14 @@ class ProjectController(FeedController):
admins = []
developers = []
for user in c.project.users():
- roles = M.ProjectRole.query.find({'_id': {'$in': M.ProjectRole.by_user(user).roles}})
+ roles = M.ProjectRole.query.find(
+ {'_id': {'$in': M.ProjectRole.by_user(user).roles}})
roles = set([r.name for r in roles])
u = dict(
- display_name=user.display_name,
- username=user.username,
- url=user.url(),
- roles=', '.join(sorted(roles)))
+ display_name=user.display_name,
+ username=user.username,
+ url=user.url(),
+ roles=', '.join(sorted(roles)))
if 'Admin' in roles:
admins.append(u)
elif 'Developer' in roles:
@@ -368,7 +397,8 @@ class ProjectController(FeedController):
def index(self, **kw):
mount = c.project.first_mount_visible(c.user)
activity_enabled = config.get('activitystream.enabled', False)
- activity_enabled = request.cookies.get('activitystream.enabled', activity_enabled)
+ activity_enabled = request.cookies.get(
+ 'activitystream.enabled', activity_enabled)
activity_enabled = asbool(activity_enabled)
if mount is not None:
if 'ac' in mount:
@@ -412,10 +442,10 @@ class ProjectController(FeedController):
g.credentials,
g.credentials.project_roles(project_id=c.project.root_project._id).named)
users = M.User.query.find({
- '_id': {'$in': named_roles.userids_that_reach},
- 'display_name': re.compile(r'(?i)%s' % re.escape(term)),
- 'disabled': False,
- }).sort('username').limit(10).all()
+ '_id': {'$in': named_roles.userids_that_reach},
+ 'display_name': re.compile(r'(?i)%s' % re.escape(term)),
+ 'disabled': False,
+ }).sort('username').limit(10).all()
return dict(
users=[
dict(
@@ -433,6 +463,7 @@ class ProjectController(FeedController):
} for u in c.project.users()]
}
+
class ScreenshotsController(object):
@expose()
@@ -443,6 +474,7 @@ class ScreenshotsController(object):
filename = unquote(request.path.rsplit('/', 1)[-1])
return ScreenshotController(filename), args
+
class ScreenshotController(object):
def __init__(self, filename):
@@ -462,7 +494,8 @@ class ScreenshotController(object):
project_id=c.project._id,
category='screenshot',
filename=self.filename)
- if not f: raise exc.HTTPNotFound
+ if not f:
+ raise exc.HTTPNotFound
return f
@LazyProperty
@@ -471,9 +504,11 @@ class ScreenshotController(object):
project_id=c.project._id,
category='screenshot_thumb',
filename=self.filename)
- if not f: raise exc.HTTPNotFound
+ if not f:
+ raise exc.HTTPNotFound
return f
+
def set_nav(neighborhood):
project = neighborhood.neighborhood_project
if project:
@@ -485,7 +520,9 @@ def set_nav(neighborhood):
SitemapEntry('Overview', admin_url + 'overview'),
SitemapEntry('Awards', admin_url + 'accolades')]
+
class NeighborhoodAdminController(object):
+
def __init__(self, neighborhood):
self.neighborhood = neighborhood
self.awards = NeighborhoodAwardsController(self.neighborhood)
@@ -532,11 +569,14 @@ class NeighborhoodAdminController(object):
@expose('jinja:allura:templates/neighborhood_admin_accolades.html')
def accolades(self):
set_nav(self.neighborhood)
- awards = M.Award.query.find(dict(created_by_neighborhood_id=self.neighborhood._id)).all()
+ awards = M.Award.query.find(
+ dict(created_by_neighborhood_id=self.neighborhood._id)).all()
awards_count = len(awards)
- grants = M.AwardGrant.query.find(dict(granted_by_neighborhood_id=self.neighborhood._id))
+ grants = M.AwardGrant.query.find(
+ dict(granted_by_neighborhood_id=self.neighborhood._id))
grants_count = grants.count()
- c.project_select = W.project_select(self.neighborhood.url() + '_admin/project_search')
+ c.project_select = W.project_select(
+ self.neighborhood.url() + '_admin/project_search')
return dict(
awards=awards,
awards_count=awards_count,
@@ -551,31 +591,31 @@ class NeighborhoodAdminController(object):
nbhd = self.neighborhood
c.project = nbhd.neighborhood_project
h.log_if_changed(nbhd, 'name', name,
- 'change neighborhood name to %s' % name)
+ 'change neighborhood name to %s' % name)
nbhd_redirect = kw.pop('redirect', '')
h.log_if_changed(nbhd, 'redirect', nbhd_redirect,
- 'change neighborhood redirect to %s' % nbhd_redirect)
+ 'change neighborhood redirect to %s' % nbhd_redirect)
h.log_if_changed(nbhd, 'homepage', homepage,
- 'change neighborhood homepage to %s' % homepage)
+ 'change neighborhood homepage to %s' % homepage)
h.log_if_changed(nbhd, 'css', css,
- 'change neighborhood css to %s' % css)
+ 'change neighborhood css to %s' % css)
h.log_if_changed(nbhd, 'project_template', project_template,
- 'change neighborhood project template to %s'
- % project_template)
+ 'change neighborhood project template to %s'
+ % project_template)
allow_browse = kw.get('allow_browse', False)
h.log_if_changed(nbhd, 'allow_browse', allow_browse,
- 'change neighborhood allow browse to %s'
- % allow_browse)
+ 'change neighborhood allow browse to %s'
+ % allow_browse)
show_title = kw.get('show_title', False)
h.log_if_changed(nbhd, 'show_title', show_title,
- 'change neighborhood show title to %s' % show_title)
+ 'change neighborhood show title to %s' % show_title)
project_list_url = kw.get('project_list_url', '')
h.log_if_changed(nbhd, 'project_list_url', project_list_url,
- 'change neighborhood project list url to %s'
- % project_list_url)
+ 'change neighborhood project list url to %s'
+ % project_list_url)
tracking_id = kw.get('tracking_id', '')
h.log_if_changed(nbhd, 'tracking_id', tracking_id,
- 'update neighborhood tracking_id')
+ 'update neighborhood tracking_id')
anchored_tools = kw.get('anchored_tools', '')
validate_tools = dict()
result = True
@@ -585,13 +625,14 @@ class NeighborhoodAdminController(object):
(tool.split(':')[0].lower(), tool.split(':')[1])
for tool in anchored_tools.replace(' ', '').split(','))
except Exception:
- flash('Anchored tools "%s" is invalid' % anchored_tools,'error')
+ flash('Anchored tools "%s" is invalid' %
+ anchored_tools, 'error')
result = False
-
for tool in validate_tools.keys():
if tool not in g.entry_points['tool']:
- flash('Anchored tools "%s" is invalid' % anchored_tools,'error')
+ flash('Anchored tools "%s" is invalid' %
+ anchored_tools, 'error')
result = False
if result:
h.log_if_changed(nbhd, 'anchored_tools', anchored_tools,
@@ -616,6 +657,7 @@ class NeighborhoodAdminController(object):
neighborhood=self.neighborhood,
)
+
class NeighborhoodStatsController(object):
def __init__(self, neighborhood):
@@ -624,14 +666,16 @@ class NeighborhoodStatsController(object):
@with_trailing_slash
@expose('jinja:allura:templates/neighborhood_stats.html')
def index(self, **kw):
- delete_count = M.Project.query.find(dict(neighborhood_id=self.neighborhood._id, deleted=True)).count()
+ delete_count = M.Project.query.find(
+ dict(neighborhood_id=self.neighborhood._id, deleted=True)).count()
public_count = 0
private_count = 0
last_updated_30 = 0
last_updated_60 = 0
last_updated_90 = 0
today_date = datetime.today()
- if M.Project.query.find(dict(neighborhood_id=self.neighborhood._id, deleted=False)).count() < 20000: # arbitrary limit for efficiency
+ # arbitrary limit for efficiency
+ if M.Project.query.find(dict(neighborhood_id=self.neighborhood._id, deleted=False)).count() < 20000:
for p in M.Project.query.find(dict(neighborhood_id=self.neighborhood._id, deleted=False)):
if p.private:
private_count = private_count + 1
@@ -660,7 +704,8 @@ class NeighborhoodStatsController(object):
def adminlist(self, sort='alpha', limit=25, page=0, **kw):
limit, page, start = g.handle_paging(limit, page)
- pq = M.Project.query.find(dict(neighborhood_id=self.neighborhood._id, deleted=False))
+ pq = M.Project.query.find(
+ dict(neighborhood_id=self.neighborhood._id, deleted=False))
if sort == 'alpha':
pq.sort('name')
else:
@@ -670,10 +715,12 @@ class NeighborhoodStatsController(object):
entries = []
for proj in projects:
- admin_role = M.ProjectRole.query.get(project_id=proj.root_project._id, name='Admin')
+ admin_role = M.ProjectRole.query.get(
+ project_id=proj.root_project._id, name='Admin')
if admin_role is None:
continue
- user_role_list = M.ProjectRole.query.find(dict(project_id=proj.root_project._id, name=None)).all()
+ user_role_list = M.ProjectRole.query.find(
+ dict(project_id=proj.root_project._id, name=None)).all()
for ur in user_role_list:
if ur.user is not None and admin_role._id in ur.roles:
entries.append({'project': proj, 'user': ur.user})
@@ -686,6 +733,7 @@ class NeighborhoodStatsController(object):
neighborhood=self.neighborhood,
)
+
class NeighborhoodModerateController(object):
def __init__(self, neighborhood):
@@ -697,7 +745,8 @@ class NeighborhoodModerateController(object):
@expose('jinja:allura:templates/neighborhood_moderate.html')
def index(self, **kw):
c.project = self.neighborhood.neighborhood_project
- other_nbhds = list(M.Neighborhood.query.find(dict(_id={'$ne':self.neighborhood._id})).sort('name'))
+ other_nbhds = list(M.Neighborhood.query.find(
+ dict(_id={'$ne': self.neighborhood._id})).sort('name'))
return dict(neighborhood=self.neighborhood,
neighborhoods=other_nbhds)
@@ -729,7 +778,8 @@ class NeighborhoodModerateController(object):
@expose()
@require_post()
def evict(self, pid):
- p = M.Project.query.get(shortname=pid, neighborhood_id=self.neighborhood._id, deleted=False)
+ p = M.Project.query.get(
+ shortname=pid, neighborhood_id=self.neighborhood._id, deleted=False)
if p is None:
flash("Cannot evict %s; it's not in the neighborhood"
% pid, 'error')
@@ -744,6 +794,7 @@ class NeighborhoodModerateController(object):
flash('%s evicted to Projects' % pid)
redirect('.')
+
class NeighborhoodAwardsController(object):
def __init__(self, neighborhood=None):
@@ -753,7 +804,8 @@ class NeighborhoodAwardsController(object):
@expose('jinja:allura:templates/awards.html')
def index(self, **kw):
require_access(self.neighborhood, 'admin')
- awards = M.Award.query.find(dict(created_by_neighborhood_id=self.neighborhood._id)).all()
+ awards = M.Award.query.find(
+ dict(created_by_neighborhood_id=self.neighborhood._id)).all()
return dict(awards=awards or [], count=len(awards))
@expose('jinja:allura:templates/award_not_found.html')
@@ -763,7 +815,8 @@ class NeighborhoodAwardsController(object):
@expose('jinja:allura:templates/grants.html')
def grants(self, **kw):
require_access(self.neighborhood, 'admin')
- grants = M.AwardGrant.query.find(dict(granted_by_neighborhood_id=self.neighborhood._id))
+ grants = M.AwardGrant.query.find(
+ dict(granted_by_neighborhood_id=self.neighborhood._id))
count = grants.count()
return dict(grants=grants or [], count=count)
@@ -793,7 +846,7 @@ class NeighborhoodAwardsController(object):
def grant(self, grant=None, recipient=None):
require_access(self.neighborhood, 'admin')
grant_q = M.Award.query.find(dict(short=grant,
- created_by_neighborhood_id=self.neighborhood._id)).first()
+ created_by_neighborhood_id=self.neighborhood._id)).first()
recipient_q = M.Project.query.find(dict(
neighborhood_id=self.neighborhood._id, shortname=recipient,
deleted=False)).first()
@@ -807,13 +860,14 @@ class NeighborhoodAwardsController(object):
g.post_event('project_updated')
redirect(request.referer)
+
class AwardController(object):
def __init__(self, neighborhood=None, award_id=None):
self.neighborhood = neighborhood
if award_id:
self.award = M.Award.query.find(dict(_id=ObjectId(award_id),
- created_by_neighborhood_id=self.neighborhood._id)).first()
+ created_by_neighborhood_id=self.neighborhood._id)).first()
@with_trailing_slash
@expose('jinja:allura:templates/award.html')
@@ -874,6 +928,7 @@ class AwardController(object):
self.award.delete()
redirect(request.referer)
+
class GrantController(object):
def __init__(self, neighborhood=None, award=None, recipient=None):
@@ -882,9 +937,9 @@ class GrantController(object):
self.recipient = recipient.replace('_', '/')
self.award = M.Award.query.get(_id=award._id)
self.project = M.Project.query.find(dict(shortname=self.recipient,
- neighborhood_id=self.neighborhood._id)).first()
+ neighborhood_id=self.neighborhood._id)).first()
self.grant = M.AwardGrant.query.get(award_id=self.award._id,
- granted_to_project_id=self.project._id)
+ granted_to_project_id=self.project._id)
@with_trailing_slash
@expose('jinja:allura:templates/grant.html')
@@ -915,7 +970,9 @@ class GrantController(object):
g.post_event('project_updated')
redirect(request.referer)
+
class ProjectImporterController(object):
+
def __init__(self, neighborhood, *a, **kw):
super(ProjectImporterController, self).__init__(*a, **kw)
self.neighborhood = neighborhood
http://git-wip-us.apache.org/repos/asf/incubator-allura/blob/c93733ac/Allura/allura/controllers/repository.py
----------------------------------------------------------------------
diff --git a/Allura/allura/controllers/repository.py b/Allura/allura/controllers/repository.py
index 2ca33ca..05e7202 100644
--- a/Allura/allura/controllers/repository.py
+++ b/Allura/allura/controllers/repository.py
@@ -58,20 +58,23 @@ from .base import BaseController
log = logging.getLogger(__name__)
+
def on_import():
BranchBrowser.CommitBrowserClass = CommitBrowser
CommitBrowser.TreeBrowserClass = TreeBrowser
TreeBrowser.FileBrowserClass = FileBrowser
+
class RepoRootController(BaseController, FeedController):
_discuss = AppDiscussionController()
- commit_browser_widget=SCMCommitBrowserWidget()
+ commit_browser_widget = SCMCommitBrowserWidget()
def get_feed(self, project, app, user):
query = dict(project_id=project._id, app_config_id=app.config._id)
- pname, repo = (project.shortname, app.config.options.mount_label)
+ pname, repo = (project.shortname, app.config.options.mount_label)
title = '%s %s changes' % (pname, repo)
- description = 'Recent changes to %s repository in %s project' % (repo, pname)
+ description = 'Recent changes to %s repository in %s project' % (
+ repo, pname)
return FeedArgs(query, title, app.url, description=description)
def _check_security(self):
@@ -81,7 +84,7 @@ class RepoRootController(BaseController, FeedController):
@expose()
def index(self, offset=0, branch=None, **kw):
if branch is None:
- branch=c.app.default_branch_name
+ branch = c.app.default_branch_name
redirect(c.app.repo.url_for_commit(branch, url_type='ref'))
@with_trailing_slash
@@ -94,7 +97,8 @@ class RepoRootController(BaseController, FeedController):
repo_path_parts = f.url().strip('/').split('/')
links.append(dict(
repo_url=f.url(),
- repo = '%s / %s' % (repo_path_parts[1], repo_path_parts[-1]),
+ repo='%s / %s' % (repo_path_parts[1],
+ repo_path_parts[-1]),
))
return dict(links=links)
@@ -112,13 +116,15 @@ class RepoRootController(BaseController, FeedController):
def fork(self, project_id=None, mount_point=None, mount_label=None, **kw):
# this shows the form and handles the submission
security.require_authenticated()
- if not c.app.forkable: raise exc.HTTPNotFound
+ if not c.app.forkable:
+ raise exc.HTTPNotFound
from_repo = c.app.repo
ThreadLocalORMSession.flush_all()
ThreadLocalORMSession.close_all()
from_project = c.project
to_project = M.Project.query.get(_id=ObjectId(project_id))
- mount_label = mount_label or '%s - %s' % (c.project.name, c.app.config.options.mount_label)
+ mount_label = mount_label or '%s - %s' % (c.project.name,
+ c.app.config.options.mount_label)
mount_point = (mount_point or from_project.shortname)
if request.method != 'POST' or not mount_point:
return dict(from_repo=from_repo,
@@ -137,7 +143,7 @@ class RepoRootController(BaseController, FeedController):
mount_label=mount_label,
cloned_from_project_id=from_project._id,
cloned_from_repo_id=from_repo._id)
- redirect(to_project.url()+mount_point+'/')
+ redirect(to_project.url() + mount_point + '/')
except exc.HTTPRedirection:
raise
except Exception, ex:
@@ -169,15 +175,15 @@ class RepoRootController(BaseController, FeedController):
with c.app.repo.push_upstream_context():
target_branch = c.app.default_branch_name
return {
- 'source_branch': source_branch,
- 'target_branch': target_branch,
- }
+ 'source_branch': source_branch,
+ 'target_branch': target_branch,
+ }
@expose()
@require_post()
def do_request_merge(self, **kw):
kw = self.mr_widget.to_python(kw)
- downstream=dict(
+ downstream = dict(
project_id=c.project._id,
mount_point=c.app.config.options.mount_point,
commit_id=c.app.repo.commit(kw['source_branch'])._id)
@@ -214,8 +220,9 @@ class RepoRootController(BaseController, FeedController):
@without_trailing_slash
@expose('json:')
def commit_browser_data(self, **kw):
- head_ids = [ head.object_id for head in c.app.repo.get_heads() ]
- commit_ids = [c.app.repo.rev_to_commit_id(r) for r in c.app.repo.log(head_ids, id_only=True)]
+ head_ids = [head.object_id for head in c.app.repo.get_heads()]
+ commit_ids = [c.app.repo.rev_to_commit_id(r)
+ for r in c.app.repo.log(head_ids, id_only=True)]
log.info('Grab %d commit objects by ID', len(commit_ids))
commits_by_id = {
c_obj._id: c_obj
@@ -232,25 +239,27 @@ class RepoRootController(BaseController, FeedController):
result = []
for row, oid in enumerate(topo_sort(children, parents, dates, head_ids)):
ci = commits_by_id[oid]
- url=c.app.repo.url_for_commit(Object(_id=oid))
+ url = c.app.repo.url_for_commit(Object(_id=oid))
msg_split = ci.message.splitlines()
if msg_split:
msg = msg_split[0]
else:
msg = "No commit message."
result.append(dict(
- oid=oid,
- short_id=c.app.repo.shorthand_for_commit(oid),
- row=row,
- parents=ci.parent_ids,
- message=msg,
- url=url))
+ oid=oid,
+ short_id=c.app.repo.shorthand_for_commit(oid),
+ row=row,
+ parents=ci.parent_ids,
+ message=msg,
+ url=url))
log.info('...done')
col_idx = {}
columns = []
+
def find_column(columns):
- for i,c in enumerate(columns):
- if c is None: return i
+ for i, c in enumerate(columns):
+ if c is None:
+ return i
columns.append(None)
return len(columns) - 1
for row, ci_json in enumerate(result):
@@ -263,14 +272,15 @@ class RepoRootController(BaseController, FeedController):
ci_json['column'] = colno
for p in parents[oid]:
p_col = col_idx.get(p, None)
- if p_col is not None: continue
+ if p_col is not None:
+ continue
p_col = find_column(columns)
col_idx[p] = p_col
columns[p_col] = p
built_tree = dict(
- (ci_json['oid'], ci_json) for ci_json in result)
+ (ci_json['oid'], ci_json) for ci_json in result)
return dict(
- commits=[ ci_json['oid'] for ci_json in result ],
+ commits=[ci_json['oid'] for ci_json in result],
built_tree=built_tree,
next_column=len(columns),
max_row=row)
@@ -279,7 +289,9 @@ class RepoRootController(BaseController, FeedController):
def status(self, **kw):
return dict(status=c.app.repo.status)
+
class RepoRestController(RepoRootController):
+
@expose('json:')
def index(self, **kw):
all_commits = c.app.repo._impl.new_commits(all_commits=True)
@@ -292,7 +304,7 @@ class RepoRestController(RepoRootController):
return {
'commits': [
{
- 'parents': [{'id':p} for p in commit['parents']],
+ 'parents': [{'id': p} for p in commit['parents']],
'url': c.app.repo.url_for_commit(commit['id']),
'id': commit['id'],
'message': commit['message'],
@@ -302,17 +314,18 @@ class RepoRestController(RepoRootController):
'author': {
'name': commit['authored']['name'],
'email': commit['authored']['email'],
- },
+ },
'committer': {
'name': commit['committed']['name'],
'email': commit['committed']['email'],
},
}
- for commit in revisions
- ]}
+ for commit in revisions
+ ]}
+
class MergeRequestsController(object):
- mr_filter=SCMMergeRequestFilterWidget()
+ mr_filter = SCMMergeRequestFilterWidget()
@expose('jinja:allura:templates/repo/merge_requests.html')
@validate(mr_filter)
@@ -328,18 +341,20 @@ class MergeRequestsController(object):
def _lookup(self, num, *remainder):
return MergeRequestController(num), remainder
+
class MergeRequestController(object):
- log_widget=SCMLogWidget(show_paging=False)
- thread_widget=w.Thread(
+ log_widget = SCMLogWidget(show_paging=False)
+ thread_widget = w.Thread(
page=None, limit=None, page_size=None, count=None,
style='linear')
- mr_dispose_form=SCMMergeRequestDisposeWidget()
+ mr_dispose_form = SCMMergeRequestDisposeWidget()
def __init__(self, num):
self.req = M.MergeRequest.query.get(
app_config_id=c.app.config._id,
request_number=int(num))
- if self.req is None: raise exc.HTTPNotFound
+ if self.req is None:
+ raise exc.HTTPNotFound
@expose('jinja:allura:templates/repo/merge_request.html')
def index(self, page=0, limit=250, **kw):
@@ -349,7 +364,7 @@ class MergeRequestController(object):
with self.req.push_downstream_context():
downstream_app = c.app
return dict(
- downstream_app = downstream_app,
+ downstream_app=downstream_app,
req=self.req,
page=page,
limit=limit,
@@ -376,9 +391,10 @@ class RefsController(object):
if EOR in remainder:
i = remainder.index(quote(c.app.END_OF_REF_ESCAPE))
ref = '/'.join((ref,) + remainder[:i])
- remainder = remainder[i+1:]
+ remainder = remainder[i + 1:]
return self.BranchBrowserClass(ref), remainder
+
class CommitsController(object):
@expose()
@@ -387,11 +403,12 @@ class CommitsController(object):
if EOR in remainder:
i = remainder.index(quote(c.app.END_OF_REF_ESCAPE))
ci = '/'.join((ci,) + remainder[:i])
- remainder = remainder[i+1:]
+ remainder = remainder[i + 1:]
return CommitBrowser(ci), remainder
+
class BranchBrowser(BaseController):
- CommitBrowserClass=None
+ CommitBrowserClass = None
def __init__(self, branch):
self._branch = branch
@@ -415,11 +432,12 @@ class BranchBrowser(BaseController):
ci = c.app.repo.commit(self._branch)
redirect(ci.url() + 'log/')
+
class CommitBrowser(BaseController):
- TreeBrowserClass=None
+ TreeBrowserClass = None
revision_widget = SCMRevisionWidget()
- log_widget=SCMLogWidget()
- page_list=ffw.PageList()
+ log_widget = SCMLogWidget()
+ page_list = ffw.PageList()
DEFAULT_PAGE_LIMIT = 25
def __init__(self, revision):
@@ -442,11 +460,11 @@ class CommitBrowser(BaseController):
tree = self._commit.tree
limit, page, start = g.handle_paging(limit, page,
default=self.DEFAULT_PAGE_LIMIT)
- diffs = self._commit.paged_diffs(start=start, end=start+limit)
+ diffs = self._commit.paged_diffs(start=start, end=start + limit)
result['artifacts'] = [
- (t,f) for t in ('added', 'removed', 'changed', 'copied')
- for f in diffs[t]
- if t == 'removed' or tree.get_blob_by_path(f)]
+ (t, f) for t in ('added', 'removed', 'changed', 'copied')
+ for f in diffs[t]
+ if t == 'removed' or tree.get_blob_by_path(f)]
count = diffs['total']
result.update(dict(page=page, limit=limit, count=count))
return result
@@ -478,7 +496,6 @@ class CommitBrowser(BaseController):
rev = self._commit.url().split('/')[-2]
return dict(status=c.app.repo.get_tarball_status(rev, path))
-
@expose('jinja:allura:templates/repo/log.html')
@with_trailing_slash
@validate(dict(page=validators.Int(if_empty=0, if_invalid=0),
@@ -488,10 +505,10 @@ class CommitBrowser(BaseController):
if path:
is_file = c.app.repo.is_file(path, self._commit._id)
commits = list(islice(c.app.repo.log(
- revs=self._commit._id,
- path=path,
- id_only=False,
- page_size=limit+1), limit+1))
+ revs=self._commit._id,
+ path=path,
+ id_only=False,
+ page_size=limit + 1), limit + 1))
next_commit = None
if len(commits) > limit:
next_commit = commits.pop()
@@ -509,7 +526,7 @@ class CommitBrowser(BaseController):
class TreeBrowser(BaseController, DispatchIndex):
tree_widget = SCMTreeWidget()
- FileBrowserClass=None
+ FileBrowserClass = None
subscribe_form = SubscribeForm()
def __init__(self, commit, tree, path='', parent=None):
@@ -592,10 +609,12 @@ class FileBrowser(BaseController):
if kw.pop('format', 'html') == 'raw':
return self.raw()
elif 'diff' in kw:
- tg.decorators.override_template(self.index, 'jinja:allura:templates/repo/diff.html')
+ tg.decorators.override_template(
+ self.index, 'jinja:allura:templates/repo/diff.html')
return self.diff(kw['diff'], kw.pop('diformat', None))
elif 'barediff' in kw:
- tg.decorators.override_template(self.index, 'jinja:allura:templates/repo/barediff.html')
+ tg.decorators.override_template(
+ self.index, 'jinja:allura:templates/repo/barediff.html')
return self.diff(kw['barediff'], kw.pop('diformat', None))
else:
force_display = 'force' in kw
@@ -607,7 +626,7 @@ class FileBrowser(BaseController):
prev=context.get('prev', None),
next=context.get('next', None),
force_display=force_display
- )
+ )
@expose()
def raw(self, **kw):
@@ -655,17 +674,20 @@ class FileBrowser(BaseController):
diff = ''.join(difflib.unified_diff(la, lb, adesc, bdesc))
return dict(a=a, b=b, diff=diff)
+
def topo_sort(children, parents, dates, head_ids):
to_visit = sorted(list(set(head_ids)), key=lambda x: dates[x])
visited = set()
while to_visit:
next = to_visit.pop()
- if next in visited: continue
+ if next in visited:
+ continue
visited.add(next)
yield next
for p in parents[next]:
for c in children[p]:
- if c not in visited: break
+ if c not in visited:
+ break
else:
to_visit.append(p)
http://git-wip-us.apache.org/repos/asf/incubator-allura/blob/c93733ac/Allura/allura/controllers/rest.py
----------------------------------------------------------------------
diff --git a/Allura/allura/controllers/rest.py b/Allura/allura/controllers/rest.py
index 84301df..cab7084 100644
--- a/Allura/allura/controllers/rest.py
+++ b/Allura/allura/controllers/rest.py
@@ -100,10 +100,12 @@ class RestController(object):
c.api_token = self._authenticate_request()
if c.api_token:
c.user = c.api_token.user
- neighborhood = M.Neighborhood.query.get(url_prefix = '/' + name + '/')
- if not neighborhood: raise exc.HTTPNotFound, name
+ neighborhood = M.Neighborhood.query.get(url_prefix='/' + name + '/')
+ if not neighborhood:
+ raise exc.HTTPNotFound, name
return NeighborhoodRestController(neighborhood), remainder
+
class OAuthNegotiator(object):
@LazyProperty
@@ -131,7 +133,7 @@ class OAuthNegotiator(object):
headers=request.headers,
parameters=dict(request.params),
query_string=request.query_string
- )
+ )
consumer_token = M.OAuthConsumerToken.query.get(
api_key=req['oauth_consumer_key'])
access_token = M.OAuthAccessToken.query.get(
@@ -159,7 +161,7 @@ class OAuthNegotiator(object):
headers=request.headers,
parameters=dict(request.params),
query_string=request.query_string
- )
+ )
consumer_token = M.OAuthConsumerToken.query.get(
api_key=req['oauth_consumer_key'])
if consumer_token is None:
@@ -174,7 +176,7 @@ class OAuthNegotiator(object):
req_token = M.OAuthRequestToken(
consumer_token_id=consumer_token._id,
callback=req.get('oauth_callback', 'oob')
- )
+ )
session(req_token).flush()
log.info('Saving new request token with key: %s', req_token.api_key)
return req_token.to_string()
@@ -208,7 +210,7 @@ class OAuthNegotiator(object):
url = rtok.callback + '&'
else:
url = rtok.callback + '?'
- url+='oauth_token=%s&oauth_verifier=%s' % (
+ url += 'oauth_token=%s&oauth_verifier=%s' % (
rtok.api_key, rtok.validation_pin)
redirect(url)
@@ -220,7 +222,7 @@ class OAuthNegotiator(object):
headers=request.headers,
parameters=dict(request.params),
query_string=request.query_string
- )
+ )
consumer_token = M.OAuthConsumerToken.query.get(
api_key=req['oauth_consumer_key'])
request_token = M.OAuthRequestToken.query.get(
@@ -244,12 +246,13 @@ class OAuthNegotiator(object):
log.error('Invalid signature')
raise exc.HTTPForbidden
acc_token = M.OAuthAccessToken(
- consumer_token_id=consumer_token._id,
- request_token_id=request_token._id,
- user_id=request_token.user_id,
- )
+ consumer_token_id=consumer_token._id,
+ request_token_id=request_token._id,
+ user_id=request_token.user_id,
+ )
return acc_token.to_string()
+
class NeighborhoodRestController(object):
def __init__(self, neighborhood):
@@ -259,24 +262,29 @@ class NeighborhoodRestController(object):
def _lookup(self, name, *remainder):
provider = plugin.ProjectRegistrationProvider.get()
try:
- provider.shortname_validator.to_python(name, check_allowed=False, neighborhood=self._neighborhood)
+ provider.shortname_validator.to_python(
+ name, check_allowed=False, neighborhood=self._neighborhood)
except Invalid as e:
raise exc.HTTPNotFound, name
name = self._neighborhood.shortname_prefix + name
- project = M.Project.query.get(shortname=name, neighborhood_id=self._neighborhood._id, deleted=False)
- if not project: raise exc.HTTPNotFound, name
+ project = M.Project.query.get(
+ shortname=name, neighborhood_id=self._neighborhood._id, deleted=False)
+ if not project:
+ raise exc.HTTPNotFound, name
c.project = project
return ProjectRestController(), remainder
+
class ProjectRestController(object):
@expose()
def _lookup(self, name, *remainder):
if not name:
return self, ()
- subproject = M.Project.query.get(shortname=c.project.shortname + '/' + name,
- neighborhood_id=c.project.neighborhood_id,
- deleted=False)
+ subproject = M.Project.query.get(
+ shortname=c.project.shortname + '/' + name,
+ neighborhood_id=c.project.neighborhood_id,
+ deleted=False)
if subproject:
c.project = subproject
c.app = None
@@ -288,7 +296,7 @@ class ProjectRestController(object):
if app.api_root is None:
raise exc.HTTPNotFound, name
action_logger.info('', extra=dict(
- api_key=request.params.get('api_key')))
+ api_key=request.params.get('api_key')))
return app.api_root, remainder
@expose('json:')
http://git-wip-us.apache.org/repos/asf/incubator-allura/blob/c93733ac/Allura/allura/controllers/root.py
----------------------------------------------------------------------
diff --git a/Allura/allura/controllers/root.py b/Allura/allura/controllers/root.py
index f00a596..0d7f96b 100644
--- a/Allura/allura/controllers/root.py
+++ b/Allura/allura/controllers/root.py
@@ -18,7 +18,9 @@
# under the License.
"""Main Controller"""
-import logging, string, os
+import logging
+import string
+import os
from datetime import datetime
from collections import defaultdict
@@ -54,10 +56,13 @@ log = logging.getLogger(__name__)
TGFlash.static_template = '''$('#messages').notify('%(message)s', {status: '%(status)s'});'''
+
class W:
project_summary = plw.ProjectSummary()
+
class RootController(WsgiDispatchController):
+
"""
The root controller for the allura application.
@@ -78,8 +83,8 @@ class RootController(WsgiDispatchController):
nf.admin = SiteAdminController()
search = SearchController()
rest = RestController()
- if config.get('trovecategories.enableediting', 'false')=='true':
- categories=TroveCategoryController()
+ if config.get('trovecategories.enableediting', 'false') == 'true':
+ categories = TroveCategoryController()
def __init__(self):
n_url_prefix = '/%s/' % request.path.split('/')[1]
@@ -93,9 +98,10 @@ class RootController(WsgiDispatchController):
def _setup_request(self):
c.project = c.app = None
c.memoize_cache = {}
- c.user = plugin.AuthenticationProvider.get(request).authenticate_request()
+ c.user = plugin.AuthenticationProvider.get(
+ request).authenticate_request()
assert c.user is not None, ('c.user should always be at least User.anonymous(). '
- 'Did you run `paster setup-app` to create the database?')
+ 'Did you run `paster setup-app` to create the database?')
def _cleanup_request(self):
pass
@@ -105,8 +111,9 @@ class RootController(WsgiDispatchController):
def index(self, **kw):
"""Handle the front-page."""
neighborhoods = M.Neighborhood.query.find().sort('name')
- categories = M.ProjectCategory.query.find({'parent_id':None}).sort('name').all()
+ categories = M.ProjectCategory.query.find(
+ {'parent_id': None}).sort('name').all()
c.custom_sidebar_menu = [
- SitemapEntry(cat.label, '/browse/'+cat.name) for cat in categories
+ SitemapEntry(cat.label, '/browse/' + cat.name) for cat in categories
]
- return dict(neighborhoods=neighborhoods,title="All Neighborhoods")
+ return dict(neighborhoods=neighborhoods, title="All Neighborhoods")
http://git-wip-us.apache.org/repos/asf/incubator-allura/blob/c93733ac/Allura/allura/controllers/search.py
----------------------------------------------------------------------
diff --git a/Allura/allura/controllers/search.py b/Allura/allura/controllers/search.py
index a58ee9f..7afeb4d 100644
--- a/Allura/allura/controllers/search.py
+++ b/Allura/allura/controllers/search.py
@@ -29,10 +29,12 @@ from allura import model as M
from allura.lib.widgets import project_list as plw
from allura.controllers import BaseController
+
class W:
project_summary = plw.ProjectSummary()
search_results = SearchResults()
+
class SearchController(BaseController):
@expose('jinja:allura:templates/search_index.html')
@@ -52,14 +54,17 @@ class SearchController(BaseController):
d['hide_app_project_switcher'] = True
return d
+
class ProjectBrowseController(BaseController):
+
def __init__(self, category_name=None, parent_category=None):
self.parent_category = parent_category
self.nav_stub = '/browse/'
self.additional_filters = {}
if category_name:
parent_id = parent_category and parent_category._id or None
- self.category = M.ProjectCategory.query.find(dict(name=category_name,parent_id=parent_id)).first()
+ self.category = M.ProjectCategory.query.find(
+ dict(name=category_name, parent_id=parent_id)).first()
if not self.category:
raise exc.HTTPNotFound, request.path
else:
@@ -74,33 +79,36 @@ class ProjectBrowseController(BaseController):
return title
def _build_nav(self):
- categories = M.ProjectCategory.query.find({'parent_id':None}).sort('name').all()
+ categories = M.ProjectCategory.query.find(
+ {'parent_id': None}).sort('name').all()
nav = []
for cat in categories:
nav.append(SitemapEntry(
cat.label,
- self.nav_stub+cat.name,
- ))
+ self.nav_stub + cat.name,
+ ))
if (self.category and self.category._id == cat._id and cat.subcategories) or (
- self.parent_category and self.parent_category._id == cat._id):
+ self.parent_category and self.parent_category._id == cat._id):
for subcat in cat.subcategories:
nav.append(SitemapEntry(
subcat.label,
- self.nav_stub+cat.name+'/'+subcat.name,
- ))
+ self.nav_stub + cat.name + '/' + subcat.name,
+ ))
return nav
- def _find_projects(self,sort='alpha', limit=None, start=0):
+ def _find_projects(self, sort='alpha', limit=None, start=0):
if self.category:
ids = [self.category._id]
# warning! this is written with the assumption that categories
# are only two levels deep like the existing site
if self.category.subcategories:
ids = ids + [cat._id for cat in self.category.subcategories]
- pq = M.Project.query.find(dict(category_id={'$in':ids}, deleted=False, **self.additional_filters))
+ pq = M.Project.query.find(
+ dict(category_id={'$in': ids}, deleted=False, **self.additional_filters))
else:
- pq = M.Project.query.find(dict(deleted=False, **self.additional_filters))
- if sort=='alpha':
+ pq = M.Project.query.find(
+ dict(deleted=False, **self.additional_filters))
+ if sort == 'alpha':
pq.sort('name')
else:
pq.sort('last_updated', pymongo.DESCENDING)
@@ -120,6 +128,6 @@ class ProjectBrowseController(BaseController):
def index(self, **kw):
c.project_summary = W.project_summary
projects, count = self._find_projects()
- title=self._build_title()
+ title = self._build_title()
c.custom_sidebar_menu = self._build_nav()
- return dict(projects=projects,title=title,text=None)
+ return dict(projects=projects, title=title, text=None)
http://git-wip-us.apache.org/repos/asf/incubator-allura/blob/c93733ac/Allura/allura/controllers/site_admin.py
----------------------------------------------------------------------
diff --git a/Allura/allura/controllers/site_admin.py b/Allura/allura/controllers/site_admin.py
index d7e7c0b..b61da6c 100644
--- a/Allura/allura/controllers/site_admin.py
+++ b/Allura/allura/controllers/site_admin.py
@@ -46,10 +46,12 @@ from urlparse import urlparse
log = logging.getLogger(__name__)
+
class W:
page_list = ffw.PageList()
page_size = ffw.PageSize()
+
class SiteAdminController(object):
def __init__(self):
@@ -65,10 +67,12 @@ class SiteAdminController(object):
def index(self):
neighborhoods = []
for n in M.Neighborhood.query.find():
- project_count = M.Project.query.find(dict(neighborhood_id=n._id)).count()
- configured_count = M.Project.query.find(dict(neighborhood_id=n._id, database_configured=True)).count()
+ project_count = M.Project.query.find(
+ dict(neighborhood_id=n._id)).count()
+ configured_count = M.Project.query.find(
+ dict(neighborhood_id=n._id, database_configured=True)).count()
neighborhoods.append((n.name, project_count, configured_count))
- neighborhoods.sort(key=lambda n:n[0])
+ neighborhoods.sort(key=lambda n: n[0])
return dict(neighborhoods=neighborhoods)
@expose('jinja:allura:templates/site_admin_api_tickets.html')
@@ -91,7 +95,8 @@ class SiteAdminController(object):
flash('JSON format error')
if type(caps) is not type({}):
ok = False
- flash('Capabilities must be a JSON dictionary, mapping capability name to optional discriminator(s) (or "")')
+ flash(
+ 'Capabilities must be a JSON dictionary, mapping capability name to optional discriminator(s) (or "")')
try:
expires = dateutil.parser.parse(data['expires'])
except ValueError:
@@ -100,7 +105,8 @@ class SiteAdminController(object):
if ok:
tok = None
try:
- tok = M.ApiTicket(user_id=for_user._id, capabilities=caps, expires=expires)
+ tok = M.ApiTicket(user_id=for_user._id,
+ capabilities=caps, expires=expires)
session(tok).flush()
log.info('New token: %s', tok)
flash('API Ticket created')
@@ -110,7 +116,8 @@ class SiteAdminController(object):
elif request.method == 'GET':
data = {'expires': datetime.utcnow() + timedelta(days=2)}
- data['token_list'] = M.ApiTicket.query.find().sort('mod_date', pymongo.DESCENDING).all()
+ data['token_list'] = M.ApiTicket.query.find().sort(
+ 'mod_date', pymongo.DESCENDING).all()
log.info(data['token_list'])
return data
@@ -119,7 +126,7 @@ class SiteAdminController(object):
neighborhood = M.Neighborhood.query.find({
"url_prefix": "/" + artifact_url[0] + "/"}).first()
- if artifact_url[0] == "u":
+ if artifact_url[0] == "u":
project = M.Project.query.find({
"shortname": artifact_url[0] + "/" + artifact_url[1],
"neighborhood_id": neighborhood._id}).first()
@@ -196,10 +203,10 @@ class SiteAdminController(object):
end = bson.ObjectId.from_datetime(end_dt)
nb = M.Neighborhood.query.get(name='Users')
projects = (M.Project.query.find({
- 'neighborhood_id': {'$ne': nb._id},
- 'deleted': False,
- '_id': {'$lt': start, '$gt': end},
- }).sort('_id', -1))
+ 'neighborhood_id': {'$ne': nb._id},
+ 'deleted': False,
+ '_id': {'$lt': start, '$gt': end},
+ }).sort('_id', -1))
step = start_dt - end_dt
params = request.params.copy()
params['start-dt'] = (start_dt + step).strftime('%Y/%m/%d %H:%M:%S')
@@ -226,28 +233,36 @@ class SiteAdminController(object):
if c.form_errors:
error_msg = 'Error: '
for msg in list(c.form_errors):
- names = {'prefix': 'Neighborhood prefix', 'shortname': 'Project shortname', 'mount_point': 'Repository mount point'}
+ names = {'prefix': 'Neighborhood prefix', 'shortname':
+ 'Project shortname', 'mount_point': 'Repository mount point'}
error_msg += '%s: %s ' % (names[msg], c.form_errors[msg])
flash(error_msg, 'error')
return dict(prefix=prefix, shortname=shortname, mount_point=mount_point)
nbhd = M.Neighborhood.query.get(url_prefix='/%s/' % prefix)
if not nbhd:
- flash('Neighborhood with prefix %s not found' % prefix, 'error')
+ flash('Neighborhood with prefix %s not found' %
+ prefix, 'error')
return dict(prefix=prefix, shortname=shortname, mount_point=mount_point)
- c.project = M.Project.query.get(shortname=shortname, neighborhood_id=nbhd._id)
+ c.project = M.Project.query.get(
+ shortname=shortname, neighborhood_id=nbhd._id)
if not c.project:
- flash('Project with shortname %s not found in neighborhood %s' % (shortname, nbhd.name), 'error')
+ flash(
+ 'Project with shortname %s not found in neighborhood %s' %
+ (shortname, nbhd.name), 'error')
return dict(prefix=prefix, shortname=shortname, mount_point=mount_point)
c.app = c.project.app_instance(mount_point)
if not c.app:
- flash('Mount point %s not found on project %s' % (mount_point, c.project.shortname), 'error')
+ flash('Mount point %s not found on project %s' %
+ (mount_point, c.project.shortname), 'error')
return dict(prefix=prefix, shortname=shortname, mount_point=mount_point)
source_url = c.app.config.options.get('init_from_url')
source_path = c.app.config.options.get('init_from_path')
if not (source_url or source_path):
- flash('%s does not appear to be a cloned repo' % c.app, 'error')
+ flash('%s does not appear to be a cloned repo' %
+ c.app, 'error')
return dict(prefix=prefix, shortname=shortname, mount_point=mount_point)
- allura.tasks.repo_tasks.reclone_repo.post(prefix=prefix, shortname=shortname, mount_point=mount_point)
+ allura.tasks.repo_tasks.reclone_repo.post(
+ prefix=prefix, shortname=shortname, mount_point=mount_point)
flash('Repository is being recloned')
else:
prefix = 'p'
@@ -255,6 +270,7 @@ class SiteAdminController(object):
mount_point = ''
return dict(prefix=prefix, shortname=shortname, mount_point=mount_point)
+
class TaskManagerController(object):
def _check_security(self):
@@ -274,8 +290,8 @@ class TaskManagerController(object):
minutes = int(minutes)
except ValueError as e:
minutes = 1
- start_dt = now - timedelta(minutes=(page_num-1)*minutes)
- end_dt = now - timedelta(minutes=page_num*minutes)
+ start_dt = now - timedelta(minutes=(page_num - 1) * minutes)
+ end_dt = now - timedelta(minutes=page_num * minutes)
start = bson.ObjectId.from_datetime(start_dt)
end = bson.ObjectId.from_datetime(end_dt)
query = {'_id': {'$gt': end}}
@@ -292,17 +308,19 @@ class TaskManagerController(object):
for task in tasks:
task.project = M.Project.query.get(_id=task.context.project_id)
task.user = M.User.query.get(_id=task.context.user_id)
- newer_url = tg.url(params=dict(request.params, page_num=page_num - 1)).lstrip('/')
- older_url = tg.url(params=dict(request.params, page_num=page_num + 1)).lstrip('/')
+ newer_url = tg.url(
+ params=dict(request.params, page_num=page_num - 1)).lstrip('/')
+ older_url = tg.url(
+ params=dict(request.params, page_num=page_num + 1)).lstrip('/')
return dict(
- tasks=tasks,
- page_num=page_num,
- minutes=minutes,
- newer_url=newer_url,
- older_url=older_url,
- window_start=start_dt,
- window_end=end_dt,
- )
+ tasks=tasks,
+ page_num=page_num,
+ minutes=minutes,
+ newer_url=newer_url,
+ older_url=older_url,
+ window_start=start_dt,
+ window_end=end_dt,
+ )
@expose('jinja:allura:templates/site_admin_task_view.html')
@without_trailing_slash
@@ -313,7 +331,8 @@ class TaskManagerController(object):
task = None
if task:
task.project = M.Project.query.get(_id=task.context.project_id)
- task.app_config = M.AppConfig.query.get(_id=task.context.app_config_id)
+ task.app_config = M.AppConfig.query.get(
+ _id=task.context.app_config_id)
task.user = M.User.query.get(_id=task.context.user_id)
return dict(task=task)
http://git-wip-us.apache.org/repos/asf/incubator-allura/blob/c93733ac/Allura/allura/controllers/static.py
----------------------------------------------------------------------
diff --git a/Allura/allura/controllers/static.py b/Allura/allura/controllers/static.py
index dd8c37f..100b3a5 100644
--- a/Allura/allura/controllers/static.py
+++ b/Allura/allura/controllers/static.py
@@ -49,4 +49,4 @@ class NewForgeController(object):
"""
css, md5 = g.tool_icon_css
return utils.serve_file(StringIO(css), 'tool_icon_css', 'text/css',
- etag=md5)
+ etag=md5)
http://git-wip-us.apache.org/repos/asf/incubator-allura/blob/c93733ac/Allura/allura/controllers/task.py
----------------------------------------------------------------------
diff --git a/Allura/allura/controllers/task.py b/Allura/allura/controllers/task.py
index 59234e7..3275d94 100644
--- a/Allura/allura/controllers/task.py
+++ b/Allura/allura/controllers/task.py
@@ -15,7 +15,9 @@
# specific language governing permissions and limitations
# under the License.
+
class TaskController(object):
+
'''WSGI app providing web-like RPC
The purpose of this app is to allow us to replicate the
@@ -27,4 +29,4 @@ class TaskController(object):
task = environ['task']
result = task(restore_context=False)
start_response('200 OK', [])
- return [ result ]
+ return [result]
http://git-wip-us.apache.org/repos/asf/incubator-allura/blob/c93733ac/Allura/allura/controllers/template.py
----------------------------------------------------------------------
diff --git a/Allura/allura/controllers/template.py b/Allura/allura/controllers/template.py
index ea268af..89d4b11 100644
--- a/Allura/allura/controllers/template.py
+++ b/Allura/allura/controllers/template.py
@@ -27,6 +27,7 @@ __all__ = ['TemplateController']
class TemplateController(WsgiDispatchController):
+
"""
The fallback controller for allura.
@@ -49,7 +50,7 @@ class TemplateController(WsgiDispatchController):
abort(404)
"""
-
+
def view(self, url):
"""Abort the request with a 404 HTTP status code."""
abort(404)
http://git-wip-us.apache.org/repos/asf/incubator-allura/blob/c93733ac/Allura/allura/controllers/trovecategories.py
----------------------------------------------------------------------
diff --git a/Allura/allura/controllers/trovecategories.py b/Allura/allura/controllers/trovecategories.py
index 9af28c5..21601db 100644
--- a/Allura/allura/controllers/trovecategories.py
+++ b/Allura/allura/controllers/trovecategories.py
@@ -15,7 +15,9 @@
# specific language governing permissions and limitations
# under the License.
-import logging, string, os
+import logging
+import string
+import os
from urllib import urlencode
import bson
@@ -32,16 +34,19 @@ from allura.controllers import BaseController
from allura.lib.widgets import forms
from allura.model import TroveCategory
+
class F(object):
remove_category_form = forms.RemoveTroveCategoryForm()
add_category_form = forms.AddTroveCategoryForm()
+
class TroveCategoryController(BaseController):
+
@expose()
def _lookup(self, catshortname, *remainder):
cat = M.TroveCategory.query.get(shortname=catshortname)
return TroveCategoryController(category=cat), remainder
-
+
def __init__(self, category=None):
self.category = category
super(TroveCategoryController, self).__init__()
@@ -56,15 +61,15 @@ class TroveCategoryController(BaseController):
hierarchy = []
temp_cat = self.category.parent_category
while temp_cat:
- hierarchy = [temp_cat] + hierarchy
- temp_cat = temp_cat.parent_category
+ hierarchy = [temp_cat] + hierarchy
+ temp_cat = temp_cat.parent_category
else:
l = M.TroveCategory.query.find(dict(trove_parent_id=0)).all()
selected_cat = None
hierarchy = []
return dict(
- categories=l,
- selected_cat=selected_cat,
+ categories=l,
+ selected_cat=selected_cat,
hierarchy=hierarchy)
@expose()
@@ -88,22 +93,23 @@ class TroveCategoryController(BaseController):
path = upper.fullpath + " :: " + name
show_as_skill = upper.show_as_skill
- newid=max([el.trove_cat_id for el in M.TroveCategory.query.find()]) + 1
- shortname=name.replace(" ", "_").lower()
- shortname=''.join([(c if (c in digits or c in lowercase) else "_")
- for c in shortname])
+ newid = max(
+ [el.trove_cat_id for el in M.TroveCategory.query.find()]) + 1
+ shortname = name.replace(" ", "_").lower()
+ shortname = ''.join([(c if (c in digits or c in lowercase) else "_")
+ for c in shortname])
- oldcat=M.TroveCategory.query.get(shortname=shortname)
+ oldcat = M.TroveCategory.query.get(shortname=shortname)
if oldcat:
flash('Category "%s" already exists.' % name, "error")
else:
category = M.TroveCategory(
- trove_cat_id=newid,
- trove_parent_id=upper_id,
- fullname=name,
- shortname=shortname,
- fullpath=path,
- show_as_skill=show_as_skill)
+ trove_cat_id=newid,
+ trove_parent_id=upper_id,
+ fullname=name,
+ shortname=shortname,
+ fullpath=path,
+ show_as_skill=show_as_skill)
if category:
flash('Category "%s" successfully created.' % name)
else:
@@ -121,7 +127,8 @@ class TroveCategoryController(BaseController):
cat = M.TroveCategory.query.get(trove_cat_id=int(kw['categoryid']))
if cat.trove_parent_id:
- parent=M.TroveCategory.query.get(trove_cat_id=cat.trove_parent_id)
+ parent = M.TroveCategory.query.get(
+ trove_cat_id=cat.trove_parent_id)
redirecturl = '/categories/%s' % parent.shortname
else:
redirecturl = '/categories'
@@ -131,79 +138,78 @@ class TroveCategoryController(BaseController):
flash(m, "error")
redirect(redirecturl)
return
-
+
if M.User.withskill(cat).count() > 0:
m = "This category is used as a skill by at least a user, "
m = m + "therefore it can't be removed."
flash(m, "error")
- redirect(redirecturl)
+ redirect(redirecturl)
return
if M.Project.query.get(trove_root_database=cat._id):
m = "This category is used as a database by at least a project, "
m = m + "therefore it can't be removed."
flash(m, "error")
- redirect(redirecturl)
+ redirect(redirecturl)
return
if M.Project.query.get(trove_developmentstatus=cat._id):
m = "This category is used as development status by at least a "
m = m + "project, therefore it can't be removed."
flash(m, "error")
- redirect(redirecturl)
+ redirect(redirecturl)
return
if M.Project.query.get(trove_audience=cat._id):
m = "This category is used as intended audience by at least a "
m = m + "project, therefore it can't be removed."
flash(m, "error")
- redirect(redirecturl)
+ redirect(redirecturl)
return
if M.Project.query.get(trove_license=cat._id):
m = "This category is used as a license by at least a "
m = m + "project, therefore it can't be removed."
flash(m, "error")
- redirect(redirecturl)
+ redirect(redirecturl)
return
if M.Project.query.get(trove_os=cat._id):
m = "This category is used as operating system by at least a "
m = m + "project, therefore it can't be removed."
flash(m, "error")
- redirect(redirecturl)
+ redirect(redirecturl)
return
if M.Project.query.get(trove_language=cat._id):
m = "This category is used as programming language by at least a "
m = m + "project, therefore it can't be removed."
flash(m, "error")
- redirect(redirecturl)
+ redirect(redirecturl)
return
if M.Project.query.get(trove_topic=cat._id):
m = "This category is used as a topic by at least a "
m = m + "project, therefore it can't be removed."
flash(m, "error")
- redirect(redirecturl)
+ redirect(redirecturl)
return
if M.Project.query.get(trove_natlanguage=cat._id):
m = "This category is used as a natural language by at least a "
m = m + "project, therefore it can't be removed."
flash(m, "error")
- redirect(redirecturl)
+ redirect(redirecturl)
return
if M.Project.query.get(trove_environment=cat._id):
m = "This category is used as an environment by at least a "
m = m + "project, therefore it can't be removed."
flash(m, "error")
- redirect(redirecturl)
+ redirect(redirecturl)
return
M.TroveCategory.delete(cat)
flash('Category removed.')
redirect(redirecturl)
-
http://git-wip-us.apache.org/repos/asf/incubator-allura/blob/c93733ac/Allura/allura/eventslistener.py
----------------------------------------------------------------------
diff --git a/Allura/allura/eventslistener.py b/Allura/allura/eventslistener.py
index 3924b3b..f9f7431 100644
--- a/Allura/allura/eventslistener.py
+++ b/Allura/allura/eventslistener.py
@@ -19,7 +19,10 @@
a specific entity (e.g. user, project, ...). To do so, the new classes should
overwrite the methods defined here, which will be called when the related
event happens, so that the statistics for the given entity are updated.'''
+
+
class EventsListener:
+
def newArtifact(self, art_type, art_datetime, project, user):
pass
@@ -46,7 +49,10 @@ class EventsListener:
'''This class simply allows to iterate through all the registered listeners,
so that all of them are called to update statistics.'''
+
+
class PostEvent:
+
def __init__(self, listeners):
self.listeners = listeners
@@ -58,7 +64,8 @@ class PostEvent:
self.__iterate('newArtifact', art_type, art_datetime, project, user)
def modifiedArtifact(self, art_type, art_datetime, project, user):
- self.__iterate('modifiedArtifact',art_type,art_datetime,project,user)
+ self.__iterate('modifiedArtifact', art_type,
+ art_datetime, project, user)
def newUser(self, user):
self.__iterate('newUser', user)
@@ -77,4 +84,3 @@ class PostEvent:
def addUserToOrganization(self, organization):
self.__iterate('addUserToOrganization', organization)
-