Skip to content

Commit 85a8e24

Browse files
committed
code cleanup using autopep8
1 parent 634892b commit 85a8e24

File tree

95 files changed

+263
-247
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

95 files changed

+263
-247
lines changed

Allura/allura/app.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -801,7 +801,7 @@ def get_attachment_export_path(self, path='', *args):
801801

802802
def make_dir_for_attachments(self, path):
803803
if not os.path.exists(path):
804-
os.makedirs(path)
804+
os.makedirs(path)
805805

806806
def save_attachments(self, path, attachments):
807807
self.make_dir_for_attachments(path)
@@ -835,6 +835,7 @@ def activity_extras(self):
835835

836836
class AdminControllerMixin:
837837
"""Provides common functionality admin controllers need"""
838+
838839
def _before(self, *remainder, **params):
839840
# Display app's sidebar on admin page, instead of :class:`AdminApp`'s
840841
c.app = self.app

Allura/allura/command/script.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,8 @@ def command(self):
9595
for s in self.args[3:]:
9696
s = s.lower()
9797
if s == 'production':
98-
print ('All projects always have access to prodcution tools,'
99-
' so removing from list.')
98+
print('All projects always have access to prodcution tools,'
99+
' so removing from list.')
100100
continue
101101
if s not in ('alpha', 'beta'):
102102
print('Unknown tool status %s' % s)

Allura/allura/command/taskd.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,11 +136,11 @@ def waitfunc_checks_running():
136136
waitfunc=waitfunc,
137137
only=only)
138138
if self.task:
139-
with(proctitle("taskd:{}:{}".format(
139+
with (proctitle("taskd:{}:{}".format(
140140
self.task.task_name, self.task._id))):
141141
# Build the (fake) request
142142
request_path = '/--{}--/{}/'.format(self.task.task_name,
143-
self.task._id)
143+
self.task._id)
144144
r = Request.blank(request_path,
145145
base_url=tg.config['base_url'].rstrip(
146146
'/') + request_path,

Allura/allura/config/app_cfg.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ class MinimalApplicationConfiguratorNoRegistry(ApplicationConfigurator):
6161
Copied from tg.MinimalApplicationConfigurator but without the registry
6262
since we use RegistryManager in a specific part of our middleware already
6363
"""
64+
6465
def __init__(self):
6566
super().__init__()
6667
self.register(MimeTypesConfigurationComponent, after=False)

Allura/allura/controllers/auth.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1447,9 +1447,9 @@ def index(self, **kw):
14471447
@validate(F.oauth2_application_form, error_handler=index)
14481448
def register(self, application_name=None, application_description=None, redirect_url=None, **kw):
14491449
M.OAuth2ClientApp(name=application_name,
1450-
description=application_description,
1451-
redirect_uris=[redirect_url],
1452-
user_id=c.user._id)
1450+
description=application_description,
1451+
redirect_uris=[redirect_url],
1452+
user_id=c.user._id)
14531453
flash('Oauth2 Client registered')
14541454
redirect('.')
14551455

Allura/allura/controllers/repository.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -737,7 +737,7 @@ def index(self, page=0, limit=DEFAULT_PAGE_LIMIT, **kw):
737737
# ('removed', u'bbb.txt', 'tree', None),
738738
# ('removed', u'ddd.txt', 'tree', None),
739739
# ('changed', u'ccc.txt', 'blob', True)]
740-
result['artifacts'].sort(key=lambda x: x[1]['old'] if(isinstance(x[1], dict)) else x[1])
740+
result['artifacts'].sort(key=lambda x: x[1]['old'] if (isinstance(x[1], dict)) else x[1])
741741
return result
742742

743743
@expose('jinja:allura:templates/repo/commit_basic.html')

Allura/allura/controllers/rest.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -338,12 +338,12 @@ def save_bearer_token(self, token, request: oauthlib.common.Request, *args, **kw
338338
M.OAuth2AccessToken.query.remove({'client_id': request.client_id, 'user_id': c.user._id})
339339

340340
bearer_token = M.OAuth2AccessToken(
341-
client_id = request.client_id,
342-
scopes = token.get('scope', []),
343-
access_token = token.get('access_token'),
344-
refresh_token = token.get('refresh_token'),
345-
expires_at = datetime.utcnow() + timedelta(seconds=token.get('expires_in')),
346-
user_id = authorization_code.user_id
341+
client_id=request.client_id,
342+
scopes=token.get('scope', []),
343+
access_token=token.get('access_token'),
344+
refresh_token=token.get('refresh_token'),
345+
expires_at=datetime.utcnow() + timedelta(seconds=token.get('expires_in')),
346+
user_id=authorization_code.user_id
347347
)
348348

349349
session(bearer_token).flush()
@@ -501,7 +501,7 @@ def _authenticate(self):
501501
if not valid:
502502
raise exc.HTTPUnauthorized
503503

504-
bearer_token_prefix = 'Bearer ' # noqa: S105
504+
bearer_token_prefix = 'Bearer ' # noqa: S105
505505
auth_header = req.headers.get('Authorization')
506506
if auth_header and auth_header.startswith(bearer_token_prefix):
507507
access_token = auth_header[len(bearer_token_prefix):]
@@ -512,7 +512,6 @@ def _authenticate(self):
512512
token.last_access = datetime.utcnow()
513513
return token
514514

515-
516515
@expose('jinja:allura:templates/oauth2_authorize.html')
517516
@without_trailing_slash
518517
def authorize(self, **kwargs):
@@ -524,7 +523,6 @@ def authorize(self, **kwargs):
524523
decoded_body = str(request.body, 'utf-8')
525524
json_body = json.loads(decoded_body)
526525

527-
528526
scopes, credentials = self.server.validate_authorization_request(uri=request.url, http_method=request.method, headers=request.headers, body=json_body)
529527

530528
client_id = request.params.get('client_id')

Allura/allura/controllers/site_admin.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,7 @@ def _search(self, model, fields, add_fields, q=None, f=None, page=0, limit=None,
288288
def convert_fields(obj):
289289
# throw the type away (e.g. '_s' from 'url_s')
290290
result = {}
291-
for k,val in obj.items():
291+
for k, val in obj.items():
292292
name = k.rsplit('_', 1)
293293
if len(name) == 2:
294294
name = name[0]
@@ -776,4 +776,4 @@ class StatsSiteAdminExtension(SiteAdminExtension):
776776

777777
def update_sidebar_menu(self, links):
778778
links.append(SitemapEntry('Stats', '/nf/admin/stats',
779-
ui_icon=g.icons['stats']))
779+
ui_icon=g.icons['stats']))

Allura/allura/controllers/task.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
# under the License.
1717

1818

19-
2019
import six
2120

2221

Allura/allura/eventslistener.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ def ticketEvent(self, event_type, ticket, project, user):
4747
def addUserToOrganization(self, newMembership):
4848
pass
4949

50+
5051
'''This class simply allows to iterate through all the registered listeners,
5152
so that all of them are called to update statistics.'''
5253

Allura/allura/ext/admin/widgets.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ class ScreenshotAdmin(ff.ForgeFormResponsive):
127127
ff.ForgeForm.defaults,
128128
enctype='multipart/form-data',
129129
submit_text='Upload',
130-
)
130+
)
131131

132132
@property
133133
def fields(self):
@@ -137,7 +137,7 @@ def fields(self):
137137
attrs={
138138
'accept': 'image/*',
139139
'required': 'true',
140-
}),
140+
}),
141141
ew.InputField(name='caption',
142142
field_type="text",
143143
label='Caption',

Allura/allura/lib/app_globals.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ def cached_convert(self, artifact: MappedClass, field_name: str) -> Markup:
148148
except ValueError:
149149
threshold = None
150150
log.warning('Skipping Markdown caching - The value for config param '
151-
'"markdown_cache_threshold" must be a float.')
151+
'"markdown_cache_threshold" must be a float.')
152152

153153
# Check if contains macro and never cache
154154
if self.uncacheable_macro_regex.search(source_text):
@@ -178,7 +178,7 @@ def cached_convert(self, artifact: MappedClass, field_name: str) -> Markup:
178178
log.exception('Could not get session for %s', artifact)
179179
else:
180180
with utils.skip_mod_date(artifact.__class__), \
181-
utils.skip_last_updated(artifact.__class__):
181+
utils.skip_last_updated(artifact.__class__):
182182
sess.flush(artifact)
183183
return html
184184

@@ -588,7 +588,7 @@ def user_profile_urls_with_profile_path(self):
588588
return asbool(config['user_profile_url_with_profile_path'])
589589

590590
def user_profile_disabled_tools(self):
591-
return aslist(config.get('user_prefs.disabled_tools',''), sep=',')
591+
return aslist(config.get('user_prefs.disabled_tools', ''), sep=',')
592592

593593
def app_static(self, resource, app=None):
594594
base = config['static.url_base']
@@ -666,6 +666,7 @@ def nav_logo(self):
666666
def commit_statuses_enabled(self):
667667
return asbool(config['scm.commit_statuses'])
668668

669+
669670
class Icon:
670671

671672
def __init__(self, css, title=None):

Allura/allura/lib/custom_middleware.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -496,8 +496,9 @@ def __call__(self, environ, start_response):
496496
if environ.get('csp_form_actions'):
497497
srcs += ' ' + ' '.join(environ['csp_form_actions'])
498498

499-
oauth_endpoints = ('/rest/oauth2/authorize', '/rest/oauth2/do_authorize', '/rest/oauth/authorize', '/rest/oauth/do_authorize')
500-
if not req.path.startswith(oauth_endpoints): # Do not enforce CSP for OAuth1 and OAuth2 authorization
499+
oauth_endpoints = (
500+
'/rest/oauth2/authorize', '/rest/oauth2/do_authorize', '/rest/oauth/authorize', '/rest/oauth/do_authorize')
501+
if not req.path.startswith(oauth_endpoints): # Do not enforce CSP for OAuth1 and OAuth2 authorization
501502
if asbool(self.config.get('csp.form_actions_enforce', False)):
502503
rules.add(f"form-action {srcs}")
503504
else:
@@ -516,7 +517,8 @@ def __call__(self, environ, start_response):
516517
if asbool(self.config.get('csp.script_src_enforce', False)):
517518
rules.add(f"script-src {script_srcs} {self.config.get('csp.script_src.extras','')} 'report-sample'")
518519
else:
519-
report_rules.add(f"script-src {script_srcs} {self.config.get('csp.script_src.extras','')} 'report-sample'")
520+
report_rules.add(
521+
f"script-src {script_srcs} {self.config.get('csp.script_src.extras', '')} 'report-sample'")
520522

521523
if self.config.get('csp.script_src_attr'):
522524
if asbool(self.config.get('csp.script_src_attr_enforce', False)):
@@ -581,6 +583,7 @@ def _call_wsgi_application(application, environ):
581583
"""
582584
captured = []
583585
output = []
586+
584587
def _start_response(status, headers, exc_info=None):
585588
captured[:] = [status, headers, exc_info]
586589
return output.append
@@ -607,6 +610,7 @@ class StatusCodeRedirect:
607610
purposely return a 401), set
608611
``environ['tg.status_code_redirect'] = False`` in the application.
609612
"""
613+
610614
def __init__(self, app, errors=(400, 401, 403, 404),
611615
path='/error/document'):
612616
"""Initialize the ErrorRedirect
@@ -626,7 +630,7 @@ def __init__(self, app, errors=(400, 401, 403, 404),
626630
def __call__(self, environ, start_response):
627631
status, headers, app_iter, exc_info = _call_wsgi_application(self.app, environ)
628632
if status[:3] in self.errors and \
629-
'tg.status_code_redirect' not in environ and self.error_path:
633+
'tg.status_code_redirect' not in environ and self.error_path:
630634
# Create a response object
631635
environ['tg.original_response'] = Response(status=status, headerlist=headers, app_iter=app_iter)
632636
environ['tg.original_request'] = Request(environ)

Allura/allura/lib/helpers.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1068,7 +1068,7 @@ def urlopen(url: str | urllib.request.Request, retries=3, codes=(408, 500, 502,
10681068
10691069
"""
10701070
if isinstance(url, urllib.request.Request):
1071-
url_str = url.full_url
1071+
url_str = url.full_url
10721072
else:
10731073
url_str = url
10741074
if not url_str.startswith(('http://', 'https://')):
@@ -1375,6 +1375,7 @@ def pluralize_tool_name(tool_name: string, count: int):
13751375
return f"{tool_name}{'s'[:count^1]}"
13761376
return tool_name
13771377

1378+
13781379
def parse_fediverse_address(username: str):
13791380
pieces = username.split('@')
13801381
return f'https://{pieces[-1]}/@{pieces[1]}'

Allura/allura/lib/macro.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,8 +103,8 @@ def __call__(self, s):
103103
return response
104104
except (ValueError, TypeError) as ex:
105105
log.warning('macro error. Upwards stack is %s',
106-
''.join(traceback.format_stack()),
107-
exc_info=True)
106+
''.join(traceback.format_stack()),
107+
exc_info=True)
108108
msg = html.escape(f'[[{s}]] ({repr(ex)})')
109109
return '\n<div class="error"><pre><code>%s</code></pre></div>' % msg
110110

@@ -184,7 +184,7 @@ def project_blog_posts(max_number=5, sort='timestamp', summary=False, mount_poin
184184
ago=h.ago(post.timestamp),
185185
description=summary and '&nbsp;' or g.markdown.cached_convert(post, 'text'))
186186
for post in posts if security.has_access(post, 'read', project=post.app.project) and
187-
security.has_access(post.app.project, 'read', project=post.app.project)
187+
security.has_access(post.app.project, 'read', project=post.app.project)
188188
]
189189
posts = BlogPosts(posts=output)
190190
g.resource_manager.register(posts)

Allura/allura/lib/mail_util.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050

5151
email_policy = email.policy.SMTP + email.policy.strict
5252

53+
5354
def Header(text, *more_text) -> str:
5455
'''
5556
Helper to make sure we encode headers properly
@@ -69,6 +70,7 @@ def Header(text, *more_text) -> str:
6970
hdr_text += ' ' + m
7071
return hdr_text
7172

73+
7274
def AddrHeader(fromaddr) -> str:
7375
'''Accepts any of:
7476
Header() instance

Allura/allura/lib/package_path_loader.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ def __init__(self, override_entrypoint='allura.theme.override',
145145
# TODO: How does one handle project-theme?
146146
if default_paths is None:
147147
default_paths = [
148-
#['project-theme', None],
148+
# ['project-theme', None],
149149
['site-theme', None],
150150
['allura', '/'],
151151
]
@@ -237,7 +237,7 @@ def _replace_signposts(self, paths, rules):
237237
238238
This mutates paths.
239239
"""
240-
p_idx = lambda n: [e[0] for e in paths].index(n)
240+
def p_idx(n): return [e[0] for e in paths].index(n)
241241
for target, replacement in rules.items():
242242
try:
243243
removed = paths.pop(p_idx(replacement))

Allura/allura/lib/phone/nexmo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ def post(self, url, **params):
8989
return self.error()
9090
if resp.get('status') == '0':
9191
return self.ok(request_id=resp.get('request_id'))
92-
return self.error(code=resp.get('status'), msg=resp.get('error_text'), number=params.get('number',''))
92+
return self.error(code=resp.get('status'), msg=resp.get('error_text'), number=params.get('number', ''))
9393

9494
def verify(self, number):
9595
url = urljoin(self.BASE_URL, 'verify')

Allura/allura/lib/plugin.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -635,6 +635,7 @@ def get_last_password_updated(self, user):
635635
d = self.user_registration_date(user)
636636
return d
637637

638+
638639
def ldap_conn_staysopen(who=None, cred=None):
639640
'''
640641
You must call .unbind_s() when done with this
@@ -644,6 +645,7 @@ def ldap_conn_staysopen(who=None, cred=None):
644645
cred or config['auth.ldap.admin_password'])
645646
return con
646647

648+
647649
@contextmanager
648650
def ldap_conn(who=None, cred=None):
649651
'''

Allura/allura/lib/repository.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ def sidebar_menu(self):
156156
self.repo.push_upstream_context()
157157
except Exception:
158158
log.warning('Could not get upstream repo (perhaps it is gone) for: %s %s',
159-
self.repo, self.repo.upstream_repo.name, exc_info=True)
159+
self.repo, self.repo.upstream_repo.name, exc_info=True)
160160
else:
161161
has_upstream_repo = True
162162

@@ -218,7 +218,7 @@ def sidebar_menu(self):
218218
for b in tags[:max_tags]:
219219
links.append(SitemapEntry(
220220
b.name,
221-
h.urlquote(self.repo.url_for_commit(b.name) + 'tree/'),
221+
h.urlquote(self.repo.url_for_commit(b.name) + 'tree/'),
222222
extra_html_attrs=dict(rel='nofollow')))
223223
if len(tags) > max_tags:
224224
links.append(

Allura/allura/lib/search.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ def site_admin_search(model, q, field, **kw):
225225
# escaping spaces with '\ ' isn't sufficient for display_name_t since its stored as text_general (why??)
226226
# and wouldn't handle foo@bar.com split on @ either
227227
# This should work, but doesn't for unknown reasons: q = u'{!term f=%s}%s' % (field, q)
228-
q = q.replace(':', r'\:') # Must escape the colon for IPv6 addresses
228+
q = q.replace(':', r'\:') # Must escape the colon for IPv6 addresses
229229
q = obj.translate_query(f'{field}:({q})', fields)
230230
kw['q.op'] = 'AND' # so that all terms within the () are required
231231
fq = ['type_s:%s' % model.type_s]
@@ -314,12 +314,12 @@ def add_matches(doc):
314314
text = h.get_first(m, 'text')
315315
if title:
316316
title = (markupsafe.escape(title)
317-
.replace('#ALLURA-HIGHLIGHT-START#', markupsafe.Markup('<strong>'))
318-
.replace('#ALLURA-HIGHLIGHT-END#', markupsafe.Markup('</strong>')))
317+
.replace('#ALLURA-HIGHLIGHT-START#', markupsafe.Markup('<strong>'))
318+
.replace('#ALLURA-HIGHLIGHT-END#', markupsafe.Markup('</strong>')))
319319
if text:
320320
text = (markupsafe.escape(text)
321-
.replace('#ALLURA-HIGHLIGHT-START#', markupsafe.Markup('<strong>'))
322-
.replace('#ALLURA-HIGHLIGHT-END#', markupsafe.Markup('</strong>')))
321+
.replace('#ALLURA-HIGHLIGHT-START#', markupsafe.Markup('<strong>'))
322+
.replace('#ALLURA-HIGHLIGHT-END#', markupsafe.Markup('</strong>')))
323323
doc['title_match'] = title
324324
doc['text_match'] = text or h.get_first(doc, 'text')
325325
return doc

0 commit comments

Comments
 (0)