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:
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)
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:
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:
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:
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:
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,
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)
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
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,
'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'] = [
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'
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 = {
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))
>>> 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
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_)
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):
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'):
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
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)
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:
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
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:
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
'', '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 = [
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.'])
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
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:
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()
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):
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))
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
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):
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
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
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
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):
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)
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', '-'),
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 []
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)
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,
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
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]
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:
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'
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']:
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(
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']:
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']
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:
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(
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):
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')
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'],
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
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: