Add explicit positional argument specifiers to .format() strings python2.6
authorW. Trevor King <wking@tremily.us>
Sat, 17 Nov 2012 13:16:54 +0000 (08:16 -0500)
committerW. Trevor King <wking@tremily.us>
Sat, 17 Nov 2012 13:40:00 +0000 (08:40 -0500)
This fixes issues with Python 2.6 (before the implicit specifiers
introduced by Python 2.7).

  On Fri, Nov 16, 2012 at 09:04:56AM -0600, Daniel Heater wrote:
  > ...
  > Traceback (most recent call last):
  >   File "setup.py", line 22, in <module>
  >     version='{}'.format(version.version()),
  > ValueError: zero length field name in format
  > ...

13 files changed:
libbe/bug.py
libbe/bugdir.py
libbe/command/diff.py
libbe/command/html.py
libbe/command/import_xml.py
libbe/command/serve_commands.py
libbe/command/util.py
libbe/comment.py
libbe/ui/command_line.py
libbe/util/http.py
libbe/util/wsgi.py
setup.py
test.py

index 66510ba049dcc31f82f71ea44beae8ddf03698d5..a1d456fc15dcd7a01edf9e97502f22eead96af82 100644 (file)
@@ -710,7 +710,7 @@ class Bug (settings_object.SavedSettingsObject):
                         setattr(self, attr, new)
                     elif change_exception:
                         raise ValueError(
-                            ('Merge would change {} "{}"->"{}" for bug {}'
+                            ('Merge would change {0} "{1}"->"{2}" for bug {3}'
                              ).format(attr, old, new, self.uuid))
         for estr in other.extra_strings:
             if not estr in self.extra_strings:
index 40097f714fd6562b4ec7eb242b7b6f002cfe556f..b156c28c0951cef0dd00577af13c34bccf698a15 100644 (file)
@@ -369,22 +369,22 @@ class BugDir (list, settings_object.SavedSettingsObject):
         for (k,v) in info:
             if v is not None:
                 if k in ['severities', 'active-status', 'inactive-status']:
-                    lines.append('  <{}>'.format(k))
+                    lines.append('  <{0}>'.format(k))
                     for vk,vv in v:
                         lines.extend([
                                 '    <entry>',
-                                '      <key>{}</key>'.format(
+                                '      <key>{0}</key>'.format(
                                     xml.sax.saxutils.escape(vk)),
-                                '      <value>{}</value>'.format(
+                                '      <value>{0}</value>'.format(
                                     xml.sax.saxutils.escape(vv)),
                                 '    </entry>',
                                 ])
-                    lines.append('  </{}>'.format(k))
+                    lines.append('  </{0}>'.format(k))
                 else:
                     v = xml.sax.saxutils.escape(v)
                     lines.append('  <{0}>{1}</{0}>'.format(k, v))
         for estr in self.extra_strings:
-            lines.append('  <extra-string>{}</extra-string>'.format(estr))
+            lines.append('  <extra-string>{0}</extra-string>'.format(estr))
         if show_bugs:
             for bug in self:
                 bug_xml = bug.xml(indent=indent+2, show_comments=show_comments)
@@ -470,33 +470,34 @@ class BugDir (list, settings_object.SavedSettingsObject):
                     for entry in child.getchildren():
                         if entry.tag != 'entry':
                             raise utility.InvalidXML(
-                                '{} child element {} must be <entry>'.format(
+                                '{0} child element {1} must be <entry>'.format(
                                     child.tag, entry))
                         key = value = None
                         for kv in entry.getchildren():
                             if kv.tag == 'key':
                                 if key is not None:
                                     raise utility.InvalidXML(
-                                        ('duplicate keys ({} and {}) in {}'
+                                        ('duplicate keys ({0} and {1}) in {2}'
                                          ).format(key, kv.text, child.tag))
                                 key = xml.sax.saxutils.unescape(kv.text)
                             elif kv.tag == 'value':
                                 if value is not None:
                                     raise utility.InvalidXML(
-                                        ('duplicate values ({} and {}) in {}'
+                                        ('duplicate values ({0} and {1}) '
+                                         'in {2}'
                                          ).format(
                                             value, kv.text, child.tag))
                                 value = xml.sax.saxutils.unescape(kv.text)
                             else:
                                 raise utility.InvalidXML(
-                                    ('{} child element {} must be <key> or '
+                                    ('{0} child element {1} must be <key> or '
                                      '<value>').format(child.tag, kv))
                         if key is None:
                             raise utility.InvalidXML(
-                                'no key for {}'.format(child.tag))
+                                'no key for {0}'.format(child.tag))
                         if value is None:
                             raise utility.InvalidXML(
-                                'no key for {}'.format(child.tag))
+                                'no key for {0}'.format(child.tag))
                         entries.append((key, value))
                     text = entries
                 else:
@@ -514,7 +515,7 @@ class BugDir (list, settings_object.SavedSettingsObject):
                 self.explicit_attrs.append(attr_name)
                 setattr(self, attr_name, text)
             elif verbose == True:
-                sys.stderr.write('Ignoring unknown tag {} in {}\n'.format(
+                sys.stderr.write('Ignoring unknown tag {0} in {1}\n'.format(
                         child.tag, bugdir.tag))
         if uuid != self.uuid:
             if not hasattr(self, 'alt_id') or self.alt_id == None:
@@ -633,7 +634,8 @@ class BugDir (list, settings_object.SavedSettingsObject):
                         setattr(self, attr, new)
                     elif change_exception:
                         raise ValueError(
-                            ('Merge would change {} "{}"->"{}" for bugdir {}'
+                            ('Merge would change {0} "{1}"->"{2}" '
+                             'for bugdir {3}'
                              ).format(attr, old, new, self.uuid))
         for estr in other.extra_strings:
             if not estr in self.extra_strings:
@@ -641,7 +643,7 @@ class BugDir (list, settings_object.SavedSettingsObject):
                     self.extra_strings += [estr]
                 elif change_exception:
                     raise ValueError(
-                        ('Merge would add extra string "{}" for bugdir {}'
+                        ('Merge would add extra string "{0}" for bugdir {1}'
                          ).format(estr, self.uuid))
         for o_bug in other:
             try:
@@ -659,7 +661,7 @@ class BugDir (list, settings_object.SavedSettingsObject):
                     self.append(o_bug_copy)
                 elif change_exception:
                     raise ValueError(
-                        ('Merge would add bug {} (alt: {}) to bugdir {}'
+                        ('Merge would add bug {0} (alt: {1}) to bugdir {2}'
                          ).format(o_bug.uuid, o_bug.alt_id, self.uuid))
             else:
                 s_bug.merge(o_bug, accept_changes=accept_changes,
index 1e9c396b2c13910422a0146b1b692ca730f7a2ee..730de77827df7e3c440e8afde7bf8a81f3bb5821 100644 (file)
@@ -113,7 +113,7 @@ class Diff (libbe.command.Command):
             else:
                 if old_bd_current.storage.versioned == False:
                     raise libbe.command.UserError(
-                        '{} is not revision-controlled.'.format(
+                        '{0} is not revision-controlled.'.format(
                             bugdir.storage.repo))
                 old_bd = libbe.bugdir.RevisionedBugDir(old_bd_current,revision)
         d = libbe.diff.Diff(old_bd, bugdir)
index 2b7dcf8bac27d8c4374565014adedf9dff6a7944..06529534561305782812d6c1b4e473433882229e 100644 (file)
@@ -60,9 +60,9 @@ class ServerApp (libbe.util.wsgi.WSGI_AppObject,
                  strip_email=False, generation_time=None, **kwargs):
         super(ServerApp, self).__init__(
             urls=[
-                (r'^{}$'.format(index_file), self.index),
+                (r'^{0}$'.format(index_file), self.index),
                 (r'^style.css$', self.style),
-                (r'^([^/]+)/([^/]+)/{}'.format(index_file), self.bug),
+                (r'^([^/]+)/([^/]+)/{0}'.format(index_file), self.bug),
                 ],
             **kwargs)
         self.bugdirs = bugdirs
@@ -101,7 +101,7 @@ class ServerApp (libbe.util.wsgi.WSGI_AppObject,
         bugs.sort()
         if self.logger:
             self.logger.log(
-                self.log_level, 'generate {} index file for {} bugs'.format(
+                self.log_level, 'generate {0} index file for {1} bugs'.format(
                     bug_type, len(bugs)))
         template_info = {
             'title': self.title,
@@ -117,7 +117,7 @@ class ServerApp (libbe.util.wsgi.WSGI_AppObject,
             'index_file': self._index_file,
             'generation_time': self._generation_time(),
             }
-        template_info['{}_class'.format(bug_type)] = 'tab sel'
+        template_info['{0}_class'.format(bug_type)] = 'tab sel'
         if bug_type == 'target':
             template = self.template.get_template('target_index.html')
             template_info['targets'] = [
@@ -135,13 +135,13 @@ class ServerApp (libbe.util.wsgi.WSGI_AppObject,
             bugdir_id,bug_id = environ['be-server.url_args']
         except:
             raise libbe.util.wsgi.HandlerError(404, 'Not Found')
-        user_id = '{}/{}'.format(bugdir_id, bug_id)
+        user_id = '{0}/{1}'.format(bugdir_id, bug_id)
         bugdir,bug,comment = (
             libbe.command.util.bugdir_bug_comment_from_user_id(
                 self.bugdirs, user_id))
         if self.logger:
             self.logger.log(
-                self.log_level, 'generate bug file for {}/{}'.format(
+                self.log_level, 'generate bug file for {0}/{1}'.format(
                     bugdir.uuid, bug.uuid))
         if bug.severity == 'target':
             index_type = 'target'
@@ -152,7 +152,7 @@ class ServerApp (libbe.util.wsgi.WSGI_AppObject,
         target = libbe.command.target.bug_target(self.bugdirs, bug)
         if target == bug:  # e.g. when bug.severity == 'target'
             target = None
-        up_link = '../../{}?type={}'.format(self._index_file, index_type)
+        up_link = '../../{0}?type={1}'.format(self._index_file, index_type)
         bug.load_comments(load_full=True)
         bug.comment_root.sort(cmp=libbe.comment.cmp_time, reverse=True)
         template_info = {
@@ -207,7 +207,7 @@ class ServerApp (libbe.util.wsgi.WSGI_AppObject,
             min_length=self.min_id_length)
 
     def bug_dir(self, bug):
-        return '{}/{}'.format(
+        return '{0}/{1}'.format(
             self._truncated_bugdir_id(bug.bugdir),
             self._truncated_bug_id(bug))
 
@@ -777,9 +777,9 @@ class HTML (libbe.util.wsgi.ServerCommand):
     >>> for bug in sorted(bugdir):
     ...     if os.path.exists(os.path.join(
     ...             export_path, bugdir.uuid, bug.uuid, 'index.html')):
-    ...         print('got {}'.format(bug.uuid))
+    ...         print('got {0}'.format(bug.uuid))
     ...     else:
-    ...         print('missing {}'.format(bug.uuid))
+    ...         print('missing {0}'.format(bug.uuid))
     got a
     got b
 
@@ -916,7 +916,7 @@ will exit after the dump without serving anything over the wire.
                 path_array.extend(segments)
                 bug_dir_path = os.path.join(*path_array)
                 path_array.append(app._index_file)
-                url = '{}/{}'.format(bug_dir_url, app._index_file)
+                url = '{0}/{1}'.format(bug_dir_url, app._index_file)
                 content = self._get_content(caller, app, url)
                 for url_,path_ in url_mappings:
                     content = content.replace(url_, path_)
@@ -929,7 +929,7 @@ will exit after the dump without serving anything over the wire.
             return caller.getURL(app=app, path=path, data_dict=data_dict)
         except libbe.util.wsgi.HandlerError:
             self.stdout.write(
-                'error retrieving {} with {}\n'.format(path, data_dict))
+                'error retrieving {0} with {1}\n'.format(path, data_dict))
             raise
 
     def _make_dir(self, dir_path):
@@ -939,7 +939,7 @@ will exit after the dump without serving anything over the wire.
                 os.makedirs(dir_path)
             except:
                 raise libbe.command.UserError(
-                    'Cannot create output directory "{}".'.format(dir_path))
+                    'Cannot create output directory "{0}".'.format(dir_path))
         return dir_path
 
     def _write_file(self, content, path_array, mode='w'):
index a16b0b0c18c6bfb5d0fb77222056ee3d05c9a0bb..9223bd591bc240c0fecdf67aa1aa93de761e658a 100644 (file)
@@ -155,11 +155,11 @@ class Import_XML (libbe.command.Command):
                     libbe.command.util.bug_from_uuid(bugdirs, new.alt_id)
                 except libbe.bugdir.NoBugMatches:
                     raise AssertionError(
-                        "bug {} (alt: {}) wasn't added to {}".format(
+                        "bug {0} (alt: {1}) wasn't added to {2}".format(
                             new.uuid, new.alt_id, root_bugdir.id.user()))
         for new in root_bugdirs:
             assert new.uuid in bugdirs or new.alt_id in bugdirs, (
-                "bugdir {} wasn't added to {}".format(
+                "bugdir {0} wasn't added to {1}".format(
                     new.uuid, sorted(bugdirs.keys())))
 
         # save new information
@@ -204,10 +204,10 @@ class Import_XML (libbe.command.Command):
                         version[child.tag] = text
                     else:
                         sys.stderr.write(
-                            'ignoring unknown tag {} in {}\n'.format(
+                            'ignoring unknown tag {0} in {1}\n'.format(
                                 gchild.tag, child.tag))
             else:
-                sys.stderr.write('ignoring unknown tag {} in {}\n'.format(
+                sys.stderr.write('ignoring unknown tag {0} in {1}\n'.format(
                         child.tag, be_xml.tag))
         return (version, root_bugdirs, root_bugs, root_comments)
 
@@ -218,7 +218,7 @@ class Import_XML (libbe.command.Command):
             return
         if bug is None:
             raise libbe.command.UserError(
-                'No root bug for merging comments:\n{}'.format(
+                'No root bug for merging comments:\n{0}'.format(
                     '\n\n'.join([c.string() for c in comments])))
         bug.load_comments(load_full=True)
         if root_comment.uuid == libbe.comment.INVALID_UUID:
index 30b4a6926ed69db54c10209245506aee3a9f407d..fd19a6110c19c6d55276656dfee2b9ce24486ab0 100644 (file)
@@ -93,7 +93,8 @@ class ServerApp (libbe.util.wsgi.WSGI_AppObject,
             Class = libbe.command.get_command_class(command_name=name)
         except libbe.command.UnknownCommand, e:
             raise libbe.util.wsgi.HandlerError(
-                libbe.util.http.HTTP_USER_ERROR, 'UnknownCommand {}'.format(e))
+                libbe.util.http.HTTP_USER_ERROR,
+                'UnknownCommand {0}'.format(e))
         command = Class(ui=self.ui)
         self.ui.setup_command(command)
         arguments = [option.arg for option in command.options
index 6f7b92e4782883b36462aa48eaee0cb46f609bab..7606044e847ed1320b688e7e2c2f00a0693d9c3b 100644 (file)
@@ -203,11 +203,11 @@ def bugdir_bug_comment_from_user_id(bugdirs, id):
     p = libbe.util.id.parse_user(bugdirs, id)
     if not p['type'] in ['bugdir', 'bug', 'comment']:
         raise libbe.command.UserError(
-            '{} is a {} id, not a bugdir, bug, or comment id'.format(
+            '{0} is a {1} id, not a bugdir, bug, or comment id'.format(
                 id, p['type']))
     if p['bugdir'] not in bugdirs:
         raise libbe.command.UserError(
-            "{} doesn't belong to any bugdirs in {}".format(
+            "{0} doesn't belong to any bugdirs in {1}".format(
                 id, sorted(bugdirs.keys())))
     bugdir = bugdirs[p['bugdir']]
     if p['bugdir'] != bugdir.uuid:
index a669e4e5012e180f229ca324426dbee53d64994b..79b9de3eab88565e5ee547acb3350ee2b648c3ba 100644 (file)
@@ -471,7 +471,7 @@ class Comment (Tree, settings_object.SavedSettingsObject):
                         setattr(self, attr, new)
                     elif change_exception:
                         raise ValueError(
-                            ('Merge would change {} "{}"->"{}" for comment {}'
+                            ('Merge would change {0} "{1}"->"{2}" for comment {3}'
                              ).format(attr, old, new, self.uuid))
         if self.alt_id == self.uuid:
             self.alt_id = None
index d94da80c5586dda3bd8a8b6c59c839c85008d6ca..f6528070dd80f8bd3026dcdec02c206e3f346048 100644 (file)
@@ -266,7 +266,8 @@ class BE (libbe.command.Command):
                '', 'Commands:']
         for name, desc in cmdlist:
             numExtraSpaces = longest_cmd_len-len(name)
-            ret.append('be {}{}    {}'.format(name, ' '*numExtraSpaces, desc))
+            ret.append('be {0}{1}    {2}'.format(
+                    name, ' '*numExtraSpaces, desc))
 
         ret.extend(['', 'Topics:'])
         topic_list = [
@@ -275,7 +276,7 @@ class BE (libbe.command.Command):
         longest_topic_len = max([len(name) for name,desc in topic_list])
         for name,desc in topic_list:
             extra_spaces = longest_topic_len - len(name)
-            ret.append('{}{}    {}'.format(name, ' '*extra_spaces, desc))
+            ret.append('{0}{1}    {2}'.format(name, ' '*extra_spaces, desc))
 
         ret.extend(['', 'Run', '  be help [command|topic]',
                     'for more information.'])
index a1ab06a4e4ea2597ab797f55f3696c79959f2a5d..ff2793d87a9b2f950eb5fdab0ce596296363eaf7 100644 (file)
@@ -59,7 +59,7 @@ class HTTPError (Exception):
     def __str__(self):
         if self.msg is None:
             if self.error is None:
-                return 'Unknown HTTP error: {}'.format(self.url)
+                return 'Unknown HTTP error: {0}'.format(self.url)
             return str(self.error)
         return self.msg
 
@@ -93,7 +93,7 @@ def get_post_url(url, get=True, data=None, data_dict=None, headers=[],
             if data_dict != {}:
                 # encode get parameters in the url
                 param_string = urllib.urlencode(data_dict)
-                url = '{}?{}'.format(url, param_string)
+                url = '{0}?{1}'.format(url, param_string)
         else:
             data = urllib.urlencode(data_dict)
     else:
@@ -109,15 +109,15 @@ def get_post_url(url, get=True, data=None, data_dict=None, headers=[],
             lines = ['The server reported a user error (HTTPError)']
         else:
             lines = ['The server reported an error (HTTPError)']
-        lines.append('URL: {}'.format(url))
+        lines.append('URL: {0}'.format(url))
         if hasattr(e, 'reason'):
-            lines.append('Reason: {}'.format(e.reason))
-        lines.append('Error code: {}'.format(e.code))
+            lines.append('Reason: {0}'.format(e.reason))
+        lines.append('Error code: {0}'.format(e.code))
         msg = '\n'.join(lines)
         raise HTTPError(error=e, url=url, msg=msg)
     except urllib2.URLError, e:
-        msg = ('We failed to connect to the server (URLError).\nURL: {}\n'
-               'Reason: {}').format(url, e.reason)
+        msg = ('We failed to connect to the server (URLError).\nURL: {0}\n'
+               'Reason: {1}').format(url, e.reason)
         raise HTTPError(error=e, url=url, msg=msg)
     page = response.read()
     final_url = response.geturl()
@@ -133,7 +133,7 @@ if TESTING:
             url = 'http://bugseverywhere.org/'
             page,final_url,info = get_post_url(url=url)
             self.failUnless(final_url == url,
-                'Redirect?\n  Expected: "{}"\n  Got:      "{}"'.format(
+                'Redirect?\n  Expected: "{0}"\n  Got:      "{1}"'.format(
                     url, final_url))
 
         def test_get_redirect(self):
@@ -141,5 +141,5 @@ if TESTING:
             expected = 'http://physics.drexel.edu/~wking/'
             page,final_url,info = get_post_url(url=url)
             self.failUnless(final_url == expected,
-                'Redirect?\n  Expected: "{}"\n  Got:      "{}"'.format(
+                'Redirect?\n  Expected: "{0}"\n  Got:      "{1}"'.format(
                     expected, final_url))
index 8f407e45031a72c2dcbde052c61d0c35e564919f..e33f9e987c8cf09b3e528d672169e27c2841dec7 100644 (file)
@@ -80,7 +80,7 @@ if libbe.TESTING == True:
 
 class HandlerError (Exception):
     def __init__(self, code, msg, headers=[]):
-        super(HandlerError, self).__init__('{} {}'.format(code, msg))
+        super(HandlerError, self).__init__('{0} {1}'.format(code, msg))
         self.code = code
         self.msg = msg
         self.headers = headers
@@ -89,7 +89,7 @@ class HandlerError (Exception):
 class Unauthenticated (HandlerError):
     def __init__(self, realm, msg='User Not Authenticated', headers=[]):
         super(Unauthenticated, self).__init__(401, msg, headers+[
-                ('WWW-Authenticate','Basic realm="{}"'.format(realm))])
+                ('WWW-Authenticate','Basic realm="{0}"'.format(realm))])
 
 
 class Unauthorized (HandlerError):
@@ -107,7 +107,7 @@ class User (object):
                 self.passhash = self.hash(password)
         else:
             assert password is None, (
-                'Redundant password {} with passhash {}'.format(
+                'Redundant password {0} with passhash {1}'.format(
                     password, passhash))
         self.users = None
 
@@ -115,7 +115,7 @@ class User (object):
         string = string.strip()
         fields = string.split(':')
         if len(fields) != 3:
-            raise ValueError, '{}!=3 fields in "{}"'.format(
+            raise ValueError, '{0}!=3 fields in "{1}"'.format(
                 len(fields), string)
         self.uname,self.name,self.passhash = fields
 
@@ -142,7 +142,7 @@ class User (object):
     def _set_property(self, property, value):
         if self.uname == 'guest':
             raise Unauthorized(
-                'guest user not allowed to change {}'.format(property))
+                'guest user not allowed to change {0}'.format(property))
         if (getattr(self, property) != value and
             self.users is not None):
             self.users.changed = True
@@ -205,11 +205,11 @@ class WSGI_Object (object):
     def __call__(self, environ, start_response):
         if self.logger is not None:
             self.logger.log(
-                logging.DEBUG, 'entering {}'.format(self.__class__.__name__))
+                logging.DEBUG, 'entering {0}'.format(self.__class__.__name__))
         ret = self._call(environ, start_response)
         if self.logger is not None:
             self.logger.log(
-                logging.DEBUG, 'leaving {}'.format(self.__class__.__name__))
+                logging.DEBUG, 'leaving {0}'.format(self.__class__.__name__))
         return ret
 
     def _call(self, environ, start_response):
@@ -226,7 +226,7 @@ class WSGI_Object (object):
 
     def error(self, environ, start_response, error, message, headers=[]):
         """Make it easy to call start_response for errors."""
-        response = '{} {}'.format(error, message)
+        response = '{0} {1}'.format(error, message)
         self.log_request(environ, status=response, bytes=len(message))
         start_response(response,
                        [('Content-Type', 'text/plain')]+headers)
@@ -245,9 +245,9 @@ class WSGI_Object (object):
         else:
             offset = time.timezone / 60 / 60 * -100
         if offset >= 0:
-            offset = '+{:04d}'.format(offset)
+            offset = '+{0:04d}'.format(offset)
         elif offset < 0:
-            offset = '{:04d}'.format(offset)
+            offset = '{0:04d}'.format(offset)
         d = {
             'REMOTE_ADDR': environ.get('REMOTE_ADDR', '-'),
             'REMOTE_USER': environ.get('REMOTE_USER', '-'),
@@ -298,7 +298,7 @@ class HandlerErrorApp (WSGI_Middleware):
             return self.app(environ, start_response)
         except HandlerError, e:
             self.log_request(environ, status=str(e), bytes=0)
-            start_response('{} {}'.format(e.code, e.msg), e.headers)
+            start_response('{0} {1}'.format(e.code, e.msg), e.headers)
             return []
 
 
@@ -325,7 +325,7 @@ class BEExceptionApp (WSGI_Middleware):
                 libbe.util.id.InvalidIDStructure,
                 libbe.storage.InvalidID,
                 ) as e:
-            msg = '{} {}'.format(type(e).__name__, format(e))
+            msg = '{0} {1}'.format(type(e).__name__, format(e))
             raise libbe.util.wsgi.HandlerError(
                 libbe.util.http.HTTP_USER_ERROR, msg)
 
@@ -362,11 +362,12 @@ class AuthenticationApp (WSGI_Middleware):
         self.users = users
 
     def _call(self, environ, start_response):
-        environ['{}.realm'.format(self.setting)] = self.realm
+        environ['{0}.realm'.format(self.setting)] = self.realm
         try:
             username = self.authenticate(environ)
-            environ['{}.user'.format(self.setting)] = username
-            environ['{}.user.name'.format(self.setting)] = self.users[username].name
+            environ['{0}.user'.format(self.setting)] = username
+            environ['{0}.user.name'.format(self.setting)
+                    ] = self.users[username].name
             return self.app(environ, start_response)
         except Unauthorized, e:
             return self.error(environ, start_response,
@@ -422,7 +423,7 @@ class AuthenticationApp (WSGI_Middleware):
         if self.users[username].valid_login(password):
             if self.logger is not None:
                 self.logger.log(self.log_level,
-                    'Authenticated {}'.format(self.users[username].name))
+                    'Authenticated {0}'.format(self.users[username].name))
             return True
         return False
 
@@ -500,7 +501,7 @@ class WSGI_DataObject (WSGI_Object):
         if not key in data or data[key] in [None, 'None']:
             if default == HandlerError:
                 raise HandlerError(
-                    406, 'Missing {} key {}'.format(source, key))
+                    406, 'Missing {0} key {1}'.format(source, key))
             return default
         return data[key]
 
@@ -535,7 +536,7 @@ class WSGI_AppObject (WSGI_Object):
         for regexp,callback in self.urls:
             match = regexp.match(path)
             if match is not None:
-                setting = '{}.url_args'.format(self.setting)
+                setting = '{0}.url_args'.format(self.setting)
                 environ[setting] = match.groups()
                 return callback(environ, start_response)
         if self.default_handler is None:
@@ -559,10 +560,10 @@ class AdminApp (WSGI_AppObject, WSGI_DataObject, WSGI_Middleware):
         self.setting = setting
 
     def admin(self, environ, start_response):
-        if not '{}.user'.format(self.setting) in environ:
-            realm = envirion.get('{}.realm'.format(self.setting))
+        if not '{0}.user'.format(self.setting) in environ:
+            realm = envirion.get('{0}.realm'.format(self.setting))
             raise Unauthenticated(realm=realm)
-        uname = environ.get('{}.user'.format(self.setting))
+        uname = environ.get('{0}.user'.format(self.setting))
         user = self.users[uname]
         data = self.post_data(environ)
         source = 'post'
@@ -644,7 +645,7 @@ class ServerCommand (libbe.command.base.Command):
     def _run(self, **params):
         if params['daemon'] not in self._daemon_actions + [None]:
             raise libbe.command.UserError(
-                'Invalid daemon action "{}".\nValid actions:\n  {}'.format(
+                'Invalid daemon action "{0}".\nValid actions:\n  {1}'.format(
                     params['daemon'], self._daemon_actions))
         self._setup_logging(params)
         if params['daemon'] not in [None, 'start']:
@@ -678,7 +679,7 @@ class ServerCommand (libbe.command.base.Command):
         raise NotImplementedError()
 
     def _setup_logging(self, params, log_level=logging.INFO):
-        self.logger = logging.getLogger('be.{}'.format(self.name))
+        self.logger = logging.getLogger('be.{0}'.format(self.name))
         self.log_level = log_level
         if params['logfile']:
             path = os.path.abspath(os.path.expanduser(
@@ -742,21 +743,21 @@ class ServerCommand (libbe.command.base.Command):
         if pid > 0:
             os._exit(0)
         self.logger.log(
-            self.log_level, 'Daemonized with PID {}'.format(os.getpid()))
+            self.log_level, 'Daemonized with PID {0}'.format(os.getpid()))
 
     def _get_pidfile(self, params):
         params['pidfile'] = os.path.abspath(os.path.expanduser(
                 params['pidfile']))
         self.logger.log(
-            self.log_level, 'Get PID file at {}'.format(params['pidfile']))
+            self.log_level, 'Get PID file at {0}'.format(params['pidfile']))
         if os.path.exists(params['pidfile']):
             raise libbe.command.UserError(
-                'PID file {} already exists'.format(params['pidfile']))
+                'PID file {0} already exists'.format(params['pidfile']))
         pid = os.getpid()
         with open(params['pidfile'], 'w') as f:  # race between exist and open
             f.write(str(os.getpid()))            
         self.logger.log(
-            self.log_level, 'Got PID file as {}'.format(pid))
+            self.log_level, 'Got PID file as {0}'.format(pid))
 
     def _start_server(self, params, server, details):
         if params['daemon']:
@@ -800,7 +801,7 @@ class ServerCommand (libbe.command.base.Command):
         if f is None:
             self.logger.log(
                 self.log_level,
-                'SIGTERM from outside _start_server(): {}'.format(
+                'SIGTERM from outside _start_server(): {0}'.format(
                     frame.f_code))
             return  # where did this signal come from?
         params = f.f_locals['params']
@@ -817,11 +818,12 @@ class ServerCommand (libbe.command.base.Command):
                 pid = f.read().strip()
         except IOError as e:
             raise libbe.command.UserError(
-                'could not find PID file: {}'.format(e))
+                'could not find PID file: {0}'.format(e))
         pid = int(pid)
         pp = self._daemon_action_present_participle[params['daemon']].title()
         self.logger.log(
-            self.log_level, '{} daemon running on process {}'.format(pp, pid))
+            self.log_level,
+            '{0} daemon running on process {1}'.format(pp, pid))
         if params['daemon'] == 'stop':
             os.kill(pid, signal.SIGTERM)
         else:
@@ -969,8 +971,8 @@ if libbe.TESTING:
 
         def basic_auth(self, uname, password):
             """HTTP basic authorization string"""
-            return 'Basic {}'.format(
-                '{}:{}'.format(uname, password).encode('base64'))
+            return 'Basic {0}'.format(
+                '{0}:{1}'.format(uname, password).encode('base64'))
 
         def test_new_name(self):
             self.getURL(
@@ -1048,8 +1050,8 @@ def _get_cert_filenames(server_name, autogenerate=True, logger=None,
     Generate private key and certification filenames.
     get_cert_filenames(server_name) -> (pkey_filename, cert_filename)
     """
-    pkey_file = '{}.pkey'.format(server_name)
-    cert_file = '{}.cert'.format(server_name)
+    pkey_file = '{0}.pkey'.format(server_name)
+    cert_file = '{0}.cert'.format(server_name)
     if autogenerate:
         for file in [pkey_file, cert_file]:
             if not os.path.exists(file):
@@ -1154,7 +1156,7 @@ def _make_certs(server_name, logger=None, level=None):
         server_name, autogenerate=False)
     if logger != None:
         logger.log(
-            level, 'Generating certificates {} {}'.format(
+            level, 'Generating certificates {0} {1}'.format(
                 pkey_file, cert_file))
     cakey = _create_key_pair(OpenSSL.crypto.TYPE_RSA, 1024)
     careq = _create_cert_request(cakey, CN='Certificate Authority')
index cd49bf0e2caa2f31769127a8cdbc309c0f534551..b33aa3875f4a99149e76414dac6fb3085f537917 100755 (executable)
--- a/setup.py
+++ b/setup.py
@@ -19,12 +19,12 @@ if os.path.exists(man_path):
 
 setup(
     name='bugs-everywhere',
-    version='{}'.format(version.version()),
+    version='{0}'.format(version.version()),
     maintainer='W. Trevor King',
     maintainer_email='wking@tremily.us',
     url='http://bugseverywhere.org/',
     download_url=(
-        'http://downloads.bugseverywhere.org/releases/be-{}.tar.gz'.format(
+        'http://downloads.bugseverywhere.org/releases/be-{0}.tar.gz'.format(
             version.version())),
     license='GNU General Public License (GPL)',
     platforms=['all'],
diff --git a/test.py b/test.py
index 060452869c9d1c02f15c480ea769d1b55004bccb..c20123c121e85e3afc3ade216663925ff5479e90 100644 (file)
--- a/test.py
+++ b/test.py
@@ -63,7 +63,7 @@ def add_module_tests(suite, modname):
     try:
         mod = import_by_name(modname)
     except ValueError as e:
-        sys.stderr.write('Failed to import "{}"\n'.format(modname))
+        sys.stderr.write('Failed to import "{0}"\n'.format(modname))
         raise e
     if hasattr(mod, 'suite'):
         s = mod.suite
@@ -92,7 +92,7 @@ those modules and their submodules.  For example::
     parser.add_option('-q', '--quiet', action='store_true', default=False,
                       help='Run unittests in quiet mode (verbosity 1).')
     options,args = parser.parse_args()
-    sys.stderr.write('Testing BE\n{}\n'.format(version(verbose=True)))
+    sys.stderr.write('Testing BE\n{0}\n'.format(version(verbose=True)))
 
     verbosity = 2
     if options.quiet == True: