Skip to content

Commit fa7cdff

Browse files
committed
Conform to PEP8
1 parent 7026a9f commit fa7cdff

16 files changed

+265
-131
lines changed

code_comments/__init__.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,2 @@
1-
from code_comments import comment
2-
from code_comments import comment_macro
3-
from code_comments import comments
4-
from code_comments import db
5-
from code_comments import notification
6-
from code_comments import subscription
7-
from code_comments import ticket_event_listener
8-
from code_comments import web
1+
import pkg_resources
2+
pkg_resources.require('Trac >= 1.2')

code_comments/api.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
# -*- coding: utf-8 -*-
2+
13
from trac.core import Component, ExtensionPoint, Interface
24

35

code_comments/comment.py

Lines changed: 46 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,26 @@
1-
import re
1+
# -*- coding: utf-8 -*-
2+
3+
import hashlib
4+
import json
25
import locale
6+
import re
37

48
import trac.wiki.formatter
59
from trac.mimeview.api import Context
610
from time import strftime, localtime
711
from code_comments import db
812
from trac.util import Markup
913
from trac.web.href import Href
10-
from trac.test import EnvironmentStub, Mock, MockPerm
14+
from trac.test import Mock, MockPerm
1115

12-
try:
13-
import json
14-
except ImportError:
15-
import simplejson as json
1616

17-
try:
18-
import hashlib
19-
md5_hexdigest = lambda s: hashlib.md5(s).hexdigest()
20-
except ImportError:
21-
import md5
22-
md5_hexdigest = lambda s: md5.new(s).hexdigest()
17+
def md5_hexdigest(s):
18+
return hashlib.md5(s).hexdigest()
2319

2420

2521
VERSION = 1
2622

23+
2724
class Comment:
2825
columns = [column.name for column in db.schema['code_comments'].columns]
2926

@@ -40,7 +37,7 @@ def __init__(self, req, env, data):
4037
self.req = req
4138
if self._empty('version'):
4239
self.version = VERSION
43-
if self._empty( 'path' ):
40+
if self._empty('path'):
4441
self.path = ''
4542
self.html = format_to_html(self.req, self.env, self.text)
4643
email = self.email_map().get(self.author, '[email protected]')
@@ -64,17 +61,25 @@ def email_map(self):
6461
return Comment._email_map
6562

6663
def validate(self):
67-
missing = [column_name for column_name in self.required if self._empty(column_name)]
64+
missing = [
65+
column_name
66+
for column_name in self.required if self._empty(column_name)
67+
]
6868
if missing:
69-
raise ValueError("Comment column(s) missing: %s" % ', '.join(missing))
69+
raise ValueError("Comment column(s) missing: %s"
70+
% ', '.join(missing))
7071

7172
def href(self):
7273
if self.is_comment_to_file:
73-
href = self.req.href.browser(self.path, rev=self.revision, codecomment=self.id)
74+
href = self.req.href.browser(self.path, rev=self.revision,
75+
codecomment=self.id)
7476
elif self.is_comment_to_changeset:
7577
href = self.req.href.changeset(self.revision, codecomment=self.id)
7678
elif self.is_comment_to_attachment:
77-
href = self.req.href('/attachment/ticket/%d/%s' % (self.attachment_ticket, self.attachment_filename), codecomment=self.id)
79+
href = self.req.href('/attachment/ticket/%d/%s'
80+
% (self.attachment_ticket,
81+
self.attachment_filename),
82+
codecomment=self.id)
7883
if self.line and not self.is_comment_to_changeset:
7984
href += '#L' + str(self.line)
8085
return href
@@ -96,7 +101,8 @@ def link_text(self):
96101

97102
def changeset_link_text(self):
98103
if 0 != self.line:
99-
return 'Changeset @%d#L%d (in %s)' % ( self.revision, self.line, self.path )
104+
return 'Changeset @%d#L%d (in %s)' % (self.revision, self.line,
105+
self.path)
100106
else:
101107
return 'Changeset @%s' % self.revision
102108

@@ -109,8 +115,8 @@ def trac_link(self):
109115
return 'source:' + self.link_text()
110116

111117
def attachment_info(self):
112-
info = { 'ticket': None, 'filename': None }
113-
if not self.path.startswith( 'attachment' ):
118+
info = {'ticket': None, 'filename': None}
119+
if not self.path.startswith('attachment'):
114120
return info
115121
match = re.match(r'attachment:/ticket/(\d+)/(.*)', self.path)
116122
if not match:
@@ -124,17 +130,20 @@ def path_link_tag(self):
124130

125131
def formatted_date(self):
126132
encoding = locale.getlocale()[1] if locale.getlocale()[1] else 'utf-8'
127-
return strftime('%d %b %Y, %H:%M', localtime(self.time)).decode(encoding)
133+
return strftime('%d %b %Y, %H:%M',
134+
localtime(self.time)).decode(encoding)
128135

129136
def get_ticket_relations(self):
130-
relations = set()
131-
db = self.env.get_db_cnx()
132-
cursor = db.cursor()
133-
query = """SELECT ticket FROM ticket_custom WHERE name = 'code_comment_relation' AND
134-
(value LIKE '%(comment_id)d' OR
135-
value LIKE '%(comment_id)d,%%' OR
136-
value LIKE '%%,%(comment_id)d' OR value LIKE '%%,%(comment_id)d,%%')""" % {'comment_id': self.id}
137+
query = """
138+
SELECT ticket FROM ticket_custom
139+
WHERE name = 'code_comment_relation' AND
140+
(VALUE LIKE '%(comment_id)d' OR
141+
VALUE LIKE '%(comment_id)d,%%' OR
142+
VALUE LIKE '%%,%(comment_id)d' OR
143+
VALUE LIKE '%%,%(comment_id)d,%%')
144+
""" % {'comment_id': self.id}
137145
result = {}
146+
138147
@self.env.with_transaction()
139148
def get_ticket_ids(db):
140149
cursor = db.cursor()
@@ -153,17 +162,24 @@ def delete_comment(db):
153162
cursor = db.cursor()
154163
cursor.execute("DELETE FROM code_comments WHERE id=%s", [self.id])
155164

165+
156166
class CommentJSONEncoder(json.JSONEncoder):
157167
def default(self, o):
158168
if isinstance(o, Comment):
159-
for_json = dict([(name, getattr(o, name)) for name in o.__dict__ if isinstance(getattr(o, name), (basestring, int, list, dict))])
169+
for_json = dict([
170+
(name, getattr(o, name))
171+
for name in o.__dict__
172+
if isinstance(getattr(o, name), (basestring, int, list, dict))
173+
])
160174
for_json['formatted_date'] = o.formatted_date()
161175
for_json['permalink'] = o.href()
162176
return for_json
163177
else:
164178
return json.JSONEncoder.default(self, o)
165179

180+
166181
def format_to_html(req, env, text):
167-
req = Mock(href=Href('/'), abs_href=Href('http://www.example.com/'), authname='anonymous', perm=MockPerm(), args={})
182+
req = Mock(href=Href('/'), abs_href=Href('http://www.example.com/'),
183+
authname='anonymous', perm=MockPerm(), args={})
168184
context = Context.from_request(req)
169185
return trac.wiki.formatter.format_to_html(env, context, text)

code_comments/comment_macro.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,24 @@
1+
# -*- coding: utf-8 -*-
2+
13
from code_comments.comments import Comments
24
from genshi.builder import tag
35
from trac.wiki.macros import WikiMacroBase
46

7+
58
class CodeCommentLinkMacro(WikiMacroBase):
69
"""CodeCommentLink macro.
710
This macro is used to embed a comment link in a ticket or wiki page:
811
[[CodeCommentLink(5)]]
912
where the number in the parentheses is the comment ID.
1013
"""
11-
14+
1215
revision = "$Rev$"
1316
url = "$URL$"
1417
re = r'\[\[CodeCommentLink\((\d+)\)\]\]'
15-
18+
1619
def expand_macro(self, formatter, name, text, args):
1720
try:
1821
comment = Comments(formatter.req, formatter.env).by_id(text)
1922
return tag.a(comment.link_text(), href=comment.href())
2023
except:
21-
return ''
24+
return ''

code_comments/comments.py

Lines changed: 40 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1+
# -*- coding: utf-8 -*-
2+
13
import os.path
24
from time import time
5+
36
from code_comments.api import CodeCommentSystem
47
from code_comments.comment import Comment
58

9+
610
class Comments:
711

812
FILTER_MAX_PATH_DEPTH = 2
@@ -22,28 +26,37 @@ def get_filter_values(self):
2226
}
2327

2428
def get_all_paths(self, comments):
25-
get_directory = lambda path: '/'.join(os.path.split(path)[0].split('/')[:self.FILTER_MAX_PATH_DEPTH])
26-
return sorted(set([get_directory(comment.path) for comment in comments if get_directory(comment.path)]))
29+
def get_directory(path):
30+
parts = os.path.split(path)[0].split('/')
31+
return '/'.join(parts[:self.FILTER_MAX_PATH_DEPTH])
32+
paths = [
33+
get_directory(comment.path)
34+
for comment in comments if get_directory(comment.path)
35+
]
36+
return sorted(set(paths))
2737

2838
def get_all_comment_authors(self, comments):
2939
return sorted(list(set([comment.author for comment in comments])))
3040

3141
def select(self, *query):
3242
result = {}
43+
3344
@self.env.with_transaction()
3445
def get_comments(db):
3546
cursor = db.cursor()
3647
cursor.execute(*query)
3748
result['comments'] = cursor.fetchall()
3849
return [self.comment_from_row(row) for row in result['comments']]
3950

40-
def count(self, args = {}):
41-
conditions_str, values = self.get_condition_str_and_corresponding_values(args)
51+
def count(self, args={}):
52+
conditions_str, values = \
53+
self.get_condition_str_and_corresponding_values(args)
4254
where = ''
4355
if conditions_str:
44-
where = 'WHERE '+conditions_str
56+
where = 'WHERE ' + conditions_str
4557
query = 'SELECT COUNT(*) FROM code_comments ' + where
4658
result = {}
59+
4760
@self.env.with_transaction()
4861
def get_comment_count(db):
4962
cursor = db.cursor()
@@ -58,22 +71,26 @@ def by_id(self, id):
5871
return self.select("SELECT * FROM code_comments WHERE id=%s", [id])[0]
5972

6073
def assert_name(self, name):
61-
if not name in Comment.columns:
74+
if name not in Comment.columns:
6275
raise ValueError("Column '%s' doesn't exist." % name)
6376

64-
def search(self, args, order = 'ASC', per_page = None, page = 1, order_by = 'time'):
77+
def search(self, args, order='ASC', per_page=None, page=1,
78+
order_by='time'):
6579
if order_by not in self.valid_sorting_methods:
6680
order_by = 'time'
67-
conditions_str, values = self.get_condition_str_and_corresponding_values(args)
81+
conditions_str, values = \
82+
self.get_condition_str_and_corresponding_values(args)
6883
where = ''
6984
limit = ''
7085
if conditions_str:
71-
where = 'WHERE '+conditions_str
86+
where = 'WHERE ' + conditions_str
7287
if order != 'ASC':
7388
order = 'DESC'
7489
if per_page:
75-
limit = ' LIMIT %d OFFSET %d' % (per_page, (page - 1)*per_page)
76-
return self.select('SELECT * FROM code_comments ' + where + ' ORDER BY ' + order_by + ' ' + order + limit, values)
90+
limit = ' LIMIT %d OFFSET %d' % (per_page, (page - 1) * per_page)
91+
return self.select('SELECT * FROM code_comments ' + where +
92+
' ORDER BY ' + order_by + ' ' + order + limit,
93+
values)
7794

7895
def get_condition_str_and_corresponding_values(self, args):
7996
conditions = []
@@ -88,18 +105,20 @@ def get_condition_str_and_corresponding_values(self, args):
88105
name = name.replace('__lt', '')
89106
conditions.append(name + ' < %s')
90107
elif name.endswith('__prefix'):
91-
values.append(args[name].replace('%', '\\%').replace('_', '\\_') + '%')
108+
values.append(
109+
args[name].replace('%', '\\%').replace('_', '\\_') + '%')
92110
name = name.replace('__prefix', '')
93111
conditions.append(name + ' LIKE %s')
94112
elif name.endswith('__in'):
95113
items = [item.strip() for item in args[name].split(',')]
96114
name = name.replace('__in', '')
97115
for item in items:
98116
values.append(item)
99-
conditions.append(name + ' IN (' + ','.join(['%s']*len(items)) + ')')
117+
conditions.append(
118+
name + ' IN (' + ','.join(['%s'] * len(items)) + ')')
100119
else:
101120
conditions.append(name + ' = %s')
102-
# don't let SQL injections in - make sure the name is an existing comment column
121+
# Prevent SQL injections: make sure name is an existing column
103122
self.assert_name(name)
104123
conditions_str = ' AND '.join(conditions)
105124
return conditions_str, values
@@ -108,14 +127,17 @@ def create(self, args):
108127
comment = Comment(self.req, self.env, args)
109128
comment.validate()
110129
comment.time = int(time())
111-
column_names_to_insert = [column_name for column_name in comment.columns if column_name != 'id']
112-
values = [getattr(comment, column_name) for column_name in column_names_to_insert]
130+
column_names_to_insert = [n for n in comment.columns if n != 'id']
131+
values = [getattr(comment, n) for n in column_names_to_insert]
113132
comment_id = [None]
133+
114134
@self.env.with_transaction()
115135
def insert_comment(db):
116136
cursor = db.cursor()
117-
sql = "INSERT INTO code_comments (%s) values(%s)" % (', '.join(column_names_to_insert), ', '.join(['%s'] * len(values)))
118-
self.env.log.debug(sql)
137+
sql = """
138+
INSERT INTO code_comments (%s) VALUES(%s)
139+
""" % (', '.join(column_names_to_insert),
140+
', '.join(['%s'] * len(values)))
119141
cursor.execute(sql, values)
120142
comment_id[0] = db.get_last_id(cursor, 'code_comments')
121143

code_comments/db.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
# -*- coding: utf-8 -*-
2+
13
from trac.core import Component, implements
24
from trac.db.schema import Table, Column, Index
35
from trac.env import IEnvironmentSetupParticipant
@@ -132,19 +134,22 @@ def upgrade_environment(self, db):
132134
if current_ver == 0:
133135
create_tables(self.env, db)
134136
else:
135-
while current_ver+1 <= db_version:
136-
upgrade_map[current_ver+1](self.env, db)
137+
while current_ver + 1 <= db_version:
138+
upgrade_map[current_ver + 1](self.env, db)
137139
current_ver += 1
138140
cursor = db.cursor()
139-
cursor.execute(
140-
"UPDATE system SET value=%s WHERE name='code_comments_schema_version'",
141-
str(db_version))
141+
cursor.execute("""
142+
UPDATE system SET value=%s
143+
WHERE name='code_comments_schema_version'
144+
""", str(db_version))
142145

143146
def _get_version(self, db):
144147
cursor = db.cursor()
145148
try:
146-
sql = "SELECT value FROM system WHERE name='code_comments_schema_version'"
147-
cursor.execute(sql)
149+
cursor.execute("""
150+
SELECT value FROM system
151+
WHERE name='code_comments_schema_version'
152+
""")
148153
for row in cursor:
149154
return int(row[0])
150155
return 0

code_comments/htdocs/backbone-min.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

code_comments/notification.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
# -*- coding: utf-8 -*-
2+
13
from trac.config import BoolOption
24
from trac.core import Component, implements
35
from trac.notification import NotifyEmail

0 commit comments

Comments
 (0)