Anonymous avatar Anonymous committed ee721b6

Code cleanup

Comments (0)

Files changed (7)

svntrac/Browser.py

 from Href import href
 import perm
 
-class Browser (Module):
+class Browser(Module):
     template_name = 'browser.template'
 
     def __init__(self, config, args, pool):
         Module.__init__(self, config, args, pool)
-        
-        if args.has_key('rev'):
-            self.rev = args['rev']
-        else:
-            self.rev = None
-        
-        if args.has_key('path'):
-            self.path = args['path']
-        else:
-            self.path = '/'
+
+        self.rev = dict_get_with_default(args, 'rev', None)
+        self.path = dict_get_with_default(args, 'path', '/')
     
-    def get_info (self, path, revision):
+    def get_info(self, path, revision):
         """
         Extracts information for a given path and revision
         """
         root = fs.revision_root(self.fs_ptr, revision, self.pool)
-        entries = fs.dir_entries (root, path, self.pool)
+        entries = fs.dir_entries(root, path, self.pool)
         info = []
         for item in entries.keys():
             fullpath = path + item
                                     util.SVN_PROP_REVISION_DATE,
                                     self.pool)
             if date:
-                date = format_date (date, self.pool)
+                date = format_date(date, self.pool)
             else:
                 date = ""
 
             info.append(item)
         return info
             
-    def pretty_size (self, size):
+    def pretty_size(self, size):
         if size < 1024:
             return '%d bytes' % size
         elif size < 1024 * 1024:
         else:
             return '%d MB' % (size / 1024 / 1024)
         
-    def print_item (self, out, item, idx):
+    def print_item(self, out, item, idx):
         if idx % 2:
-            out.write ('<tr class="item-row-even">\n')
+            out.write('<tr class="item-row-even">\n')
         else:
-            out.write ('<tr class="item-row-odd">\n')
+            out.write('<tr class="item-row-odd">\n')
         if item['is_dir']:
-            out.write ('<td class="icon-column"><img src="%s" width="16" height="16"></td>'
-                       % (self.namespace['htdocs_location'] + '/folder.png'))
-            out.write ('<td class="name-column"><a href="%s">%s</a></td>'
+            out.write('<td class="icon-column"><a href="%s"><img src="%s" width="16" height="16"></a></td>'
+                       % (href.browser(item['fullpath']),
+                          self.namespace['htdocs_location'] + '/folder.png'))
+            out.write('<td class="name-column"><a href="%s">%s</a></td>'
                        % (href.browser(item['fullpath']), item['name']))
-            out.write ('<td class="size-column">&nbsp;</td>')
-            out.write ('<td class="rev-column">%s</td>' %
+            out.write('<td class="size-column">&nbsp;</td>')
+            out.write('<td class="rev-column">%s</td>' %
                        item['created_rev'])
         else:
-            out.write ('<td class="icon-column"><img src="%s" width="16" height="16"></td>'
-                       % (self.namespace['htdocs_location'] + '/file.png'))
-            out.write ('<td class="name-column"><a href="%s">%s</a></td>'
+            out.write('<td class="icon-column"><a href="%s"><img src="%s" width="16" height="16"></a></td>'
+                       % (href.log(item['fullpath']),
+                          self.namespace['htdocs_location'] + '/file.png'))
+            out.write('<td class="name-column"><a href="%s">%s</a></td>'
                        % (href.log(item['fullpath']), item['name']))
-            out.write ('<td class="size-column">%s</td>' %
+            out.write('<td class="size-column">%s</td>' %
                        self.pretty_size(item['size']))
-            out.write ('<td class="rev-column"><a href="%s">%s</a></td>'
+            out.write('<td class="rev-column"><a href="%s">%s</a></td>'
                        % (href.file(item['fullpath'],
                                                 item['created_rev']),
                           item['created_rev']))
-        out.write ('<td class="date-column">%s</td>' % item['date'])
-        out.write ('\n</tr>\n')
+        out.write('<td class="date-column">%s</td>' % item['date'])
+        out.write('\n</tr>\n')
 
-    def get_path_links (self):
+    def get_path_links(self):
         list = self.path[1:].split('/')
         path = '/'
         str  = '<a href="%s">/</a>' % href.browser('/')
             str = str + '<a href="%s">%s/</a>' % (href.browser(path), part)
         return str
     
-    def render (self):
+    def render(self):
         perm.assert_permission (perm.BROWSER_VIEW)
         
         if not self.rev:
         else:
             rev = int(self.rev)
             
-        info = self.get_info (self.path, rev)
-        info.sort (lambda x, y: cmp(x['name'], y['name']))
-        info.sort (lambda x, y: cmp(y['is_dir'], x['is_dir']))
+        info = self.get_info(self.path, rev)
+        info.sort(lambda x, y: cmp(x['name'], y['name']))
+        info.sort(lambda x, y: cmp(y['is_dir'], x['is_dir']))
 
         out = StringIO.StringIO()
         idx = 0
         # print a '..' list item
         if self.path != '/':
             parent = string.join(self.path.split('/')[:-2], '/') + '/'
-            out.write ('<tr class="item-row-odd">\n')
-            out.write ('<td class="icon-column"><img src="%s" width="16" height="16"></td>'
-                       % (self.namespace['htdocs_location'] + '/folder.png'))
-            out.write ('<td class="name-column"><a href="%s">..</a></td><td class="size-column">&nbsp;</td><td class="rev-column">&nbsp;</td><td class="date-column">&nbsp;</td>' %
+            out.write('<tr class="item-row-odd">\n')
+            out.write('<td class="icon-column"><a href="%s"><img src="%s" width="16" height="16"></a></td>'
+                       % (href.browser(parent),
+                          self.namespace['htdocs_location'] + '/folder.png'))
+            out.write('<td class="name-column"><a href="%s">..</a></td><td class="size-column">&nbsp;</td><td class="rev-column">&nbsp;</td><td class="date-column">&nbsp;</td>' %
                        href.browser(parent))
-            out.write ('</tr>')
+            out.write('</tr>')
             idx = 1
         # print the "ordinary" items
         for item in info:
-            self.print_item (out, item, idx)
+            self.print_item(out, item, idx)
             idx = idx + 1
 
-        self.namespace['path']        = self.path
-        self.namespace['path_links']  = self.get_path_links ()
-        self.namespace['revision']    = rev
+        self.namespace['path'] = self.path
+        self.namespace['revision'] = rev
+        self.namespace['path_links'] = self.get_path_links ()
         self.namespace['dir_entries'] = out.getvalue()
 from svn import fs, util, delta
 
 from Module import Module
+from util import dict_get_with_default
 import perm
 
 class File (Module):
 
     def __init__(self, config, args, pool):
         Module.__init__(self, config, args, pool)
-        
-        if args.has_key('rev'):
-            self.rev = args['rev']
-        else:
-            self.rev = None
-        
-        if args.has_key('path'):
-            self.path = args['path']
-        else:
-            self.path = '/'
+
+        self.rev = dict_get_with_default(args, 'rev', None)
+        self.path = dict_get_with_default(args, 'path', '/')
         
     def render (self):
         perm.assert_permission (perm.FILE_VIEW)
     def __init__(self, config, args, pool):
         Module.__init__(self, config, args, pool)
         
-        if args.has_key('path'):
-            self.path = args['path']
-        else:
-            self.path = '/'
+        self.path = dict_get_with_default(args, 'path', '/')
 
     def log_receiver (self, baton, rev, author, date, log, pool):
         item = {

svntrac/Report.py

         
     def get_info (self, id):
         cnx = db.get_connection()
-        cursor = cnx.cursor ()
+        cursor = cnx.cursor()
 
         if id == -1:
             # If no special report was requested, display
             # a list of available reports instead
-            cursor.execute ("SELECT id AS report, title "
-                            "FROM report "
-                            "ORDER BY report")
+            cursor.execute("SELECT id AS report, title "
+                           "FROM report "
+                           "ORDER BY report")
             title = 'available reports'
         else:
-            cursor.execute ('SELECT title, sql from report WHERE id=%s', id)
+            cursor.execute('SELECT title, sql from report WHERE id=%s', id)
             row = cursor.fetchone()
             title = row[0]
             sql   = row[1]
-            cursor.execute (sql)
+            cursor.execute(sql)
 
         # FIXME: fetchall should probably not be used.
         info = cursor.fetchall()
         info = map(lambda row: map(lambda x: escape(x), row), info)
         return [cols, info, title]
         
-    def render_headers (self, out, row):
+    def render_headers(self, out, row):
         """
         render a html table header with the column names from the sql query.
         """
-        out.write ('<tr>')
+        out.write('<tr>')
 	for x in row:
-	    out.write ('<th class="listing">%s</th>' % x[0])
-        out.write ('</tr>')
+	    out.write('<th class="listing">%s</th>' % x[0])
+        out.write('</tr>')
         
-    def render_row (self, out, row, cols, row_idx):
+    def render_row(self, out, row, cols, row_idx):
         """
         render one html table row from one sql result row.
 
         are hyper linked...
         """
         if row_idx % 2:
-            out.write ('<tr class="item-row-even">\n')
+            out.write('<tr class="item-row-even">\n')
         else:
-            out.write ('<tr class="item-row-odd">\n')
+            out.write('<tr class="item-row-odd">\n')
 
         idx = 0
         for value in row:
             else:
                 out.write('<td class="%s-column">%s</td>' % (cols[idx][0], value))
             idx = idx + 1
-        out.write ('</tr>')
+        out.write('</tr>')
 
-    def create_report (self, title, sql):
-        perm.assert_permission (perm.REPORT_CREATE)
+    def create_report(self, title, sql):
+        perm.assert_permission(perm.REPORT_CREATE)
 
         cnx = db.get_connection()
-        cursor = cnx.cursor ()
+        cursor = cnx.cursor()
         
-        cursor.execute ('INSERT INTO report (id, title, sql)'
+        cursor.execute('INSERT INTO report (id, title, sql)'
                         'VALUES (NULL, %s, %s)', title, sql)
-        id = cnx.db.sqlite_last_insert_rowid ()
-        cnx.commit ()
+        id = cnx.db.sqlite_last_insert_rowid()
+        cnx.commit()
         redirect (href.report(id))
 
-    def delete_report (self, id):
-        perm.assert_permission (perm.REPORT_DELETE)
+    def delete_report(self, id):
+        perm.assert_permission(perm.REPORT_DELETE)
         
         cnx = db.get_connection()
         cursor = cnx.cursor ()
 
-        cursor.execute ('DELETE FROM report WHERE id=%s', id)
-        cnx.commit ()
-        redirect (href.report())
+        cursor.execute('DELETE FROM report WHERE id=%s', id)
+        cnx.commit()
+        redirect(href.report())
 
-    def commit_changes (self, id):
+    def commit_changes(self, id):
         """
         saves report changes to the database
         """
-        perm.assert_permission (perm.REPORT_MODIFY)
+        perm.assert_permission(perm.REPORT_MODIFY)
 
         cnx = db.get_connection()
-        cursor = cnx.cursor ()
+        cursor = cnx.cursor()
 
         title = self.args['title']
         sql   = self.args['sql']
 
-        cursor.execute ('UPDATE report SET title=%s, sql=%s WHERE id=%s',
-                        title, sql, id)
-        cnx.commit ()
-        redirect (href.report(id))
+        cursor.execute('UPDATE report SET title=%s, sql=%s WHERE id=%s',
+                       title, sql, id)
+        cnx.commit()
+        redirect(href.report(id))
 
-    def render_report_editor (self, out, id, action='commit'):
+    def render_report_editor(self, out, id, action='commit'):
         cnx = db.get_connection()
         cursor = cnx.cursor()
 
         if id == -1:
             title = sql = ""
         else:
-            cursor.execute ('SELECT title, sql FROM report WHERE id=%s', id)
+            cursor.execute('SELECT title, sql FROM report WHERE id=%s', id)
             row = cursor.fetchone()
+            sql = row[1]
             title = row[0]
-            sql   = row[1]
         
-        out.write (
+        out.write(
             '<form action="%s" method="post">'
             '<input type="hidden" name="mode" value="report">'
             '<input type="hidden" name="id" value="%d">'
             '</form>' % (get_cgi_name(), id, action, title, sql)
             )
     
-    def render_report_list (self, out, id):
+    def render_report_list(self, out, id):
         """
         uses a user specified sql query to extract some information
         from the database and presents it as a html table.
         """
         try:
-            [cols, rows, title] = self.get_info (id)
+            [cols, rows, title] = self.get_info(id)
         except Exception, e:
-            out.write ('<h3>report failed: %s</h3>' % e)
-            out.write ('<p><a href="%s">edit</a></p>' % href.report(id, 'edit'))
+            out.write('<h3>report failed: %s</h3>' % e)
+            out.write('<p><a href="%s">edit</a></p>' % href.report(id, 'edit'))
             return
-        if perm.has_permission (perm.REPORT_CREATE):
-            out.write ('<a href="%s">new report</a>' % href.report(None, 'new'))
-        out.write ('<h3>%s</h3><p>' % title)
+        if perm.has_permission(perm.REPORT_CREATE):
+            out.write('<a href="%s">new report</a>' % href.report(None, 'new'))
+        out.write('<h3>%s</h3><p>' % title)
         if id != -1:
-            if perm.has_permission (perm.REPORT_MODIFY):
-                out.write ('<a href="%s">edit</a> | ' % href.report(id, 'edit'))
-            if perm.has_permission (perm.REPORT_CREATE):
-                out.write ('<a href="%s">copy</a> | ' % href.report(id, 'copy'))
-            if perm.has_permission (perm.REPORT_DELETE):
-                out.write ('<a href="%s">delete</a>' % href.report(id, 'delete'))
-        out.write ('</p>')
+            if perm.has_permission(perm.REPORT_MODIFY):
+                out.write('<a href="%s">edit</a> | ' % href.report(id, 'edit'))
+            if perm.has_permission(perm.REPORT_CREATE):
+                out.write('<a href="%s">copy</a> | ' % href.report(id, 'copy'))
+            if perm.has_permission(perm.REPORT_DELETE):
+                out.write('<a href="%s">delete</a>' % href.report(id, 'delete'))
+        out.write('</p>')
         
-        out.write ('<table class="listing" cellspacing="0" cellpadding="0">')
-        self.render_headers (out, cols)
+        out.write('<table class="listing" cellspacing="0" cellpadding="0">')
+        self.render_headers(out, cols)
         row_idx = 0
         for row in rows:
-            self.render_row (out, row, cols, row_idx)
+            self.render_row(out, row, cols, row_idx)
             row_idx = row_idx + 1
-        out.write ('</table>')
+        out.write('</table>')
 
-    def render (self):
+    def render(self):
         # did the user ask for any special report?
-        if self.args.has_key('id'):
-            id = int(self.args['id'])
-        else:
-            # show a list of available reports
-            id = -1
+        id = int(dict_get_with_default(self.args, 'id', -1))
+        action = dict_get_with_default(self.args, 'action', 'list')
 
-        if self.args.has_key('action'):
-            action = self.args['action']
-        else:
-            action = 'list'
         out = StringIO.StringIO()
 
         if action == 'create':
-            self.create_report (self.args['title'], self.args['sql'])
+            self.create_report(self.args['title'], self.args['sql'])
         elif action == 'delete':
-            self.delete_report (id)
+            self.delete_report(id)
         elif action == 'commit':
-            self.commit_changes (id)
+            self.commit_changes(id)
         elif action == 'new':
-            self.render_report_editor (out, -1, 'create')
+            self.render_report_editor(out, -1, 'create')
         elif action == 'copy':
-            self.render_report_editor (out, id, 'create')
+            self.render_report_editor(out, id, 'create')
         elif action == 'edit':
-            self.render_report_editor (out, id, 'commit')
+            self.render_report_editor(out, id, 'commit')
         else:
-            self.render_report_list (out, id)
+            self.render_report_list(out, id)
 
         self.namespace['content']  = out.getvalue()

svntrac/Ticket.py

         return out.getvalue()
     
     def render (self):
-
-        if self.args.has_key('action'):
-            action = self.args['action']
-        else:
-            action = 'view'
+        action = dict_get_with_default(self.args, 'action', 'view')
             
         if action == 'create':
             self.create_ticket ()

svntrac/svntrac.py

 import sys
 import cgi
 import warnings
-from util import set_cgi_name, set_authcgi_name
+from util import set_cgi_name, set_authcgi_name, dict_get_with_default
 from svn import util, repos, core
 import Href
 
     }
 
 def main():
-    mode = 'wiki' #default module
     db.init()
     config = db.load_config()
     set_cgi_name(config['general']['cgi_name'])
     for x in _args.keys():
 	args[x] = _args[x].value
 
-    if args.has_key('mode'):
-        mode = args['mode']
+    mode = dict_get_with_default(args, 'mode', 'wiki')
 
     module_name, constructor_name, need_svn = modules[mode]
     module = __import__(module_name, globals(),  locals(), [])
     constructor = getattr(module, constructor_name)
     module = constructor(config, args, pool)
 
-    verify_authentication (args)
+    verify_authentication(args)
     cache_permissions()
 
+    # Only open the subversion repository for the modules that really
+    # need it. This saves us some precious time.
     if need_svn:
         repos_dir = config['general']['svn_repository']
         rep = repos.svn_repos_open(repos_dir, pool)
         fs_ptr = repos.svn_repos_fs(rep)
         module.repos = rep
         module.fs_ptr = fs_ptr
-        db.sync (rep, fs_ptr, pool)
+        db.sync(rep, fs_ptr, pool)
 
     try:
         module.render()
         
     core.svn_pool_destroy(pool)
     core.apr_terminate()
-
-
         else:
             u1 = u1 + '/' + u2
     return u1
+
+def dict_get_with_default(dict, key, default):
+    """Returns dict[key] if it exists else default"""
+    if dict.has_key(key):
+        return dict[key]
+    else:
+        return default
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.