Use string concatenation instead of format()

String concatenation can at times be easier to read that format().
One should choose whichever approach is more readable.
This commit is contained in:
Anders Ingemann 2014-05-03 22:24:13 +02:00
parent 7e03dbe35d
commit f3d633780f
22 changed files with 54 additions and 56 deletions

View file

@ -84,7 +84,7 @@ class AbstractPartitionMap(FSMProxy):
for mapping in mappings:
match = regexp.match(mapping)
if match is None:
raise PartitionError('Unable to parse kpartx output: {line}'.format(line=mapping))
raise PartitionError('Unable to parse kpartx output: ' + mapping)
partition_path = os.path.join('/dev/mapper', match.group('name'))
p_idx = int(match.group('p_idx')) - 1
self.partitions[p_idx].map(partition_path)
@ -92,7 +92,7 @@ class AbstractPartitionMap(FSMProxy):
# Check if any partition was not mapped
for idx, partition in enumerate(self.partitions):
if partition.fsm.current not in ['mapped', 'formatted']:
raise PartitionError('kpartx did not map partition #{idx}'.format(idx=idx + 1))
raise PartitionError('kpartx did not map partition #' + str(idx + 1))
except PartitionError as e:
# Revert any mapping and reraise the error

View file

@ -22,8 +22,6 @@ class GPTPartition(BasePartition):
# Create the partition and then set the name of the partition afterwards
super(GPTPartition, self)._before_create(e)
# partition name only works for gpt, for msdos that becomes the part-type (primary, extended, logical)
name_command = ('name {idx} {name}'
.format(idx=self.get_index(),
name=self.name))
name_command = 'name {idx} {name}'.format(idx=self.get_index(), name=self.name)
log_check_call(['parted', '--script', e.volume.device_path,
'--', name_command])

View file

@ -21,7 +21,7 @@ def get_log_filename(manifest_path):
manifest_basename = os.path.basename(manifest_path)
manifest_name, _ = os.path.splitext(manifest_basename)
timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
filename = "{timestamp}_{name}.log".format(timestamp=timestamp, name=manifest_name)
filename = '{timestamp}_{name}.log'.format(timestamp=timestamp, name=manifest_name)
return filename

View file

@ -41,8 +41,8 @@ class Manifest(object):
self.data = load_yaml(self.path)
# Get the provider name from the manifest and load the corresponding module
provider_modname = 'bootstrapvz.providers.{provider}'.format(provider=self.data['provider'])
log.debug('Loading provider `{modname}\''.format(modname=provider_modname))
provider_modname = 'bootstrapvz.providers.' + self.data['provider']
log.debug('Loading provider ' + provider_modname)
# Create a modules dict that contains the loaded provider and plugins
import importlib
self.modules = {'provider': importlib.import_module(provider_modname),
@ -51,8 +51,8 @@ class Manifest(object):
# Run through all the plugins mentioned in the manifest and load them
if 'plugins' in self.data:
for plugin_name, plugin_data in self.data['plugins'].iteritems():
modname = 'bootstrapvz.plugins.{plugin}'.format(plugin=plugin_name)
log.debug('Loading plugin `{modname}\''.format(modname=modname))
modname = 'bootstrapvz.plugins.' + plugin_name
log.debug('Loading plugin ' + modname)
plugin = importlib.import_module(modname)
self.modules['plugins'].append(plugin)

View file

@ -24,7 +24,7 @@ class PackageList(object):
if self.target is None:
return self.name
else:
return '{name}/{target}'.format(name=self.name, target=self.target)
return self.name + '/' + self.target
class Local(object):
"""A local package

View file

@ -69,7 +69,7 @@ class Source(object):
match = regexp.match(line).groupdict()
if match is None:
from exceptions import SourceError
raise SourceError('Unable to parse source line `{line}\''.format(line=line))
raise SourceError('Unable to parse source line: ' + line)
self.type = match['type']
self.options = []
if match['options'] is not None:
@ -95,7 +95,7 @@ class Source(object):
if len(self.components) > 0:
components = ' {components}'.format(components=' '.join(self.components))
return ('{type}{options} {uri}'
' {distribution}{components}').format(type=self.type, options=options,
uri=self.uri, distribution=self.distribution,
components=components)
return ('{type}{options} {uri} {distribution}{components}'
.format(type=self.type, options=options,
uri=self.uri, distribution=self.distribution,
components=components))

View file

@ -19,7 +19,7 @@ class Task(object):
Returns:
string.
"""
return '{module}.{task}'.format(module=cls.__module__, task=cls.__name__)
return cls.__module__ + '.' + cls.__name__
def __str__(cls):
"""

View file

@ -45,7 +45,7 @@ class TaskList(object):
# Create a list for us to run
task_list = self.create_list()
# Output the tasklist
log.debug('Tasklist:\n\t{list}'.format(list='\n\t'.join(map(repr, task_list))))
log.debug('Tasklist:\n\t' + ('\n\t'.join(map(repr, task_list))))
for task in task_list:
# Tasks are not required to have a description
@ -53,7 +53,7 @@ class TaskList(object):
log.info(task.description)
else:
# If there is no description, simply coerce the task into a string and print its name
log.info('Running {task}'.format(task=task))
log.info('Running ' + str(task))
if not dry_run:
# Run the task
task.run(info)
@ -92,10 +92,10 @@ class TaskList(object):
# Node of 1 is also a strongly connected component but hardly a cycle, so we filter them out
if len(component) > 1:
cycles_found += 1
log.debug('Cycle: {list}\n'.format(list=', '.join(map(repr, component))))
log.debug('Cycle: {list}\n' + (', '.join(map(repr, component))))
if cycles_found > 0:
msg = ('{0} cycles were found in the tasklist, '
'consult the logfile for more information.'.format(cycles_found))
msg = ('{num} cycles were found in the tasklist, '
'consult the logfile for more information.'.format(num=cycles_found))
raise TaskListError(msg)
# Run a topological sort on the graph, returning an ordered list
@ -141,7 +141,7 @@ class TaskList(object):
import inspect
def walk_error(module):
raise Exception('Unable to inspect module `{module}\''.format(module=module))
raise Exception('Unable to inspect module ' + module)
walker = pkgutil.walk_packages([path], prefix, walk_error)
for _, module_name, _ in walker:
module = importlib.import_module(module_name)

View file

@ -21,7 +21,7 @@ class Bytes(object):
regex = re.compile('^(?P<qty>\d+)(?P<unit>[KMGT]i?B|B)$')
parsed = regex.match(qty_str)
if parsed is None:
raise UnitError('Unable to parse {str}'.format(str=qty_str))
raise UnitError('Unable to parse ' + qty_str)
qty = int(parsed.group('qty'))
unit = parsed.group('unit')
@ -34,7 +34,7 @@ class Bytes(object):
if unit[0] in 'KMGT':
unit = unit[0] + 'iB'
if unit not in Bytes.units:
raise UnitError('Unrecognized unit `{unit}\''.format(unit=Bytes.magnitude))
raise UnitError('Unrecognized unit: ' + unit)
if self.qty % Bytes.units[unit] != 0:
msg = 'Unable to convert {qty} bytes to a whole number in {unit}'.format(qty=self.qty, unit=unit)
raise UnitError(msg)

View file

@ -19,7 +19,7 @@ class TaskListError(Exception):
self.message = message
def __str__(self):
return 'Error in tasklist: {msg}'.format(msg=self.message)
return 'Error in tasklist: ' + self.message
class TaskError(Exception):

View file

@ -72,7 +72,7 @@ class WriteSources(Task):
list_path = os.path.join(info.root, 'etc/apt/sources.list.d/', name + '.list')
with open(list_path, 'w') as source_list:
for source in sources:
source_list.write('{line}\n'.format(line=str(source)))
source_list.write(str(source) + '\n')
class WritePreferences(Task):
@ -89,7 +89,7 @@ class WritePreferences(Task):
list_path = os.path.join(info.root, 'etc/apt/preferences.d/', name)
with open(list_path, 'w') as preference_list:
for preference in preferences:
preference_list.write('{preference}\n'.format(preference=str(preference)))
preference_list.write(str(preference) + '\n')
class DisableDaemonAutostart(Task):

View file

@ -35,7 +35,7 @@ def get_tarball_filename(info):
# Filter info.root which points at /target/volume-id, we won't ever hit anything with that in there.
hash_args = [arg for arg in arguments if arg != info.root]
tarball_id = sha1(repr(frozenset(options + hash_args))).hexdigest()[0:8]
tarball_filename = 'debootstrap-{id}.tar'.format(id=tarball_id)
tarball_filename = 'debootstrap-' + tarball_id + '.tar'
return os.path.join(info.manifest.bootstrapper['workspace'], tarball_filename)

View file

@ -22,16 +22,17 @@ class GenerateLocale(Task):
def run(cls, info):
from ..tools import sed_i
from ..tools import log_check_call
locale_gen = os.path.join(info.root, 'etc/locale.gen')
locale_str = '{locale}.{charmap} {charmap}'.format(locale=info.manifest.system['locale'],
charmap=info.manifest.system['charmap'])
search = '# ' + locale_str
sed_i(locale_gen, search, locale_str)
log_check_call(['chroot', info.root, 'locale-gen'])
lang = '{locale}.{charmap}'.format(locale=info.manifest.system['locale'],
charmap=info.manifest.system['charmap'])
locale_str = '{locale}.{charmap} {charmap}'.format(locale=info.manifest.system['locale'],
charmap=info.manifest.system['charmap'])
search = '# ' + locale_str
locale_gen = os.path.join(info.root, 'etc/locale.gen')
sed_i(locale_gen, search, locale_str)
log_check_call(['chroot', info.root, 'locale-gen'])
log_check_call(['chroot', info.root,
'update-locale', 'LANG=' + lang])

View file

@ -28,7 +28,7 @@ class Create(Task):
@classmethod
def run(cls, info):
import os.path
image_path = os.path.join(info.workspace, 'volume.{ext}'.format(ext=info.volume.extension))
image_path = os.path.join(info.workspace, 'volume.' + info.volume.extension)
info.volume.create(image_path)
@ -39,7 +39,7 @@ class MoveImage(Task):
@classmethod
def run(cls, info):
image_name = info.manifest.image['name'].format(**info.manifest_vars)
filename = '{image_name}.{ext}'.format(image_name=image_name, ext=info.volume.extension)
filename = image_name + '.' + info.volume.extension
import os.path
destination = os.path.join(info.manifest.bootstrapper['workspace'], filename)
@ -47,4 +47,4 @@ class MoveImage(Task):
shutil.move(info.volume.image_path, destination)
import logging
log = logging.getLogger(__name__)
log.info('The volume image has been moved to {image_path}'.format(image_path=destination))
log.info('The volume image has been moved to ' + destination)

View file

@ -28,7 +28,7 @@ def log_call(command, stdin=None, env=None, shell=False):
q.put((stream, line.strip()))
if stdin is not None:
log.debug(' stdin: {stdin}'.format(stdin=stdin))
log.debug(' stdin: ' + stdin)
process.stdin.write(stdin + "\n")
process.stdin.flush()
process.stdin.close()

View file

@ -22,7 +22,7 @@ class Snapshot(Task):
def mk_snapshot():
return info.volume.snapshot()
snapshot = remount(info.volume, mk_snapshot)
msg = 'A snapshot of the bootstrapped volume was created. ID: {id}'.format(id=snapshot.id)
msg = 'A snapshot of the bootstrapped volume was created. ID: ' + snapshot.id
log.info(msg)
@ -58,7 +58,7 @@ class CopyImage(Task):
def mk_snapshot():
copyfile(info.volume.image_path, destination)
remount(info.volume, mk_snapshot)
msg = 'A copy of the bootstrapped volume was created. Path: {path}'.format(path=destination)
msg = 'A copy of the bootstrapped volume was created. Path: ' + destination
log.info(msg)
@ -69,7 +69,7 @@ class CreateFromImage(Task):
@classmethod
def run(cls, info):
info.volume.image_path = os.path.join(info.workspace, 'volume.{ext}'.format(ext=info.volume.extension))
info.volume.image_path = os.path.join(info.workspace, 'volume.' + info.volume.extension)
loopback_backup_path = info.manifest.plugins['prebootstrapped']['image']
copyfile(loopback_backup_path, info.volume.image_path)

View file

@ -15,7 +15,7 @@ class CheckBoxPath(Task):
@classmethod
def run(cls, info):
box_basename = info.manifest.image['name'].format(**info.manifest_vars)
box_name = '{name}.box'.format(name=box_basename)
box_name = box_basename + '.box'
box_path = os.path.join(info.manifest.bootstrapper['workspace'], box_name)
if os.path.exists(box_path):
from bootstrapvz.common.exceptions import TaskError
@ -134,7 +134,7 @@ class PackageBox(Task):
shutil.copy(metadata_source, metadata)
from bootstrapvz.common.tools import log_check_call
disk_name = 'box-disk1.{ext}'.format(ext=info.volume.extension)
disk_name = 'box-disk1.' + info.volume.extension
disk_link = os.path.join(info._vagrant['folder'], disk_name)
log_check_call(['ln', '-s', info.volume.image_path, disk_link])
@ -148,8 +148,7 @@ class PackageBox(Task):
+ box_files
)
import logging
logging.getLogger(__name__).info('The vagrant box has been placed at {box_path}'
.format(box_path=info._vagrant['box_path']))
logging.getLogger(__name__).info('The vagrant box has been placed at ' + info._vagrant['box_path'])
@classmethod
def write_ovf(cls, info, destination, mac_address, disk_name):

View file

@ -9,7 +9,7 @@ class ConvertToVhd(Task):
@classmethod
def run(cls, info):
image_name = info.manifest.image['name'].format(**info.manifest_vars)
filename = '{image_name}.{ext}'.format(image_name=image_name, ext='vhd')
filename = image_name + '.vhd'
import os.path
destination = os.path.join(info.manifest.bootstrapper['workspace'], filename)
@ -25,4 +25,4 @@ class ConvertToVhd(Task):
os.remove(info.volume.image_path)
import logging
log = logging.getLogger(__name__)
log.info('The volume image has been moved to {image_path}'.format(image_path=destination))
log.info('The volume image has been moved to ' + destination)

View file

@ -36,7 +36,7 @@ class BundleImage(Task):
@classmethod
def run(cls, info):
bundle_name = 'bundle-{id}'.format(id=info.run_id)
bundle_name = 'bundle-' + info.run_id
info._ec2['bundle_path'] = os.path.join(info.workspace, bundle_name)
arch = {'i386': 'i386', 'amd64': 'x86_64'}.get(info.manifest.system['architecture'])
log_check_call(['euca-bundle-image',

View file

@ -30,7 +30,7 @@ class ConfigurePVGrub(Task):
if not isinstance(info.volume.partition_map, NoPartitions):
from bootstrapvz.common.tools import sed_i
root_idx = info.volume.partition_map.root.get_index()
grub_device = 'GRUB_DEVICE=/dev/xvda{idx}'.format(idx=root_idx)
grub_device = 'GRUB_DEVICE=/dev/xvda' + str(root_idx)
sed_i(script_dst, '^GRUB_DEVICE=/dev/xvda$', grub_device)
grub_root = '\troot (hd0,{idx})'.format(idx=root_idx - 1)
sed_i(script_dst, '^\troot \(hd0\)$', grub_root)

View file

@ -14,7 +14,7 @@ class CreateTarball(Task):
def run(cls, info):
import datetime
image_name = info.manifest.image['name'].format(**info.manifest_vars)
filename = '{image_name}.{ext}'.format(image_name=image_name, ext=info.volume.extension)
filename = image_name + '.' + info.volume.extension
today = datetime.datetime.today()
name_suffix = today.strftime('%Y%m%d')
image_name_format = '{lsb_distribution}-{lsb_release}-{release}-v{name_suffix}'
@ -26,7 +26,7 @@ class CreateTarball(Task):
image_name = image_name.lower()
image_name = image_name.replace(".", "-")
info._gce['image_name'] = image_name
tarball_name = '{image_name}.tar.gz'.format(image_name=image_name)
tarball_name = image_name + '.tar.gz'
tarball_path = os.path.join(info.manifest.bootstrapper['workspace'], tarball_name)
info._gce['tarball_name'] = tarball_name
info._gce['tarball_path'] = tarball_path
@ -55,7 +55,7 @@ class RegisterImage(Task):
image_description = info._gce['lsb_description']
if 'description' in info.manifest.image:
image_description = info.manifest.image['description']
log_check_call(['gcutil', '--project={}'.format(info.manifest.image['gce_project']),
log_check_call(['gcutil', '--project=' + info.manifest.image['gce_project'],
'addimage', info._gce['image_name'],
info.manifest.image['gcs_destination'] + info._gce['tarball_name'],
'--description={}'.format(image_description)])
'--description=' + image_description])

View file

@ -31,7 +31,7 @@ class AddGuestAdditionsPackages(Task):
from bootstrapvz.common.tools import log_check_call
[kernel_version] = log_check_call(['chroot', info.root,
'uname', '-r'])
kernel_headers_pkg = 'linux-headers-{version}'.format(version=kernel_version)
kernel_headers_pkg = 'linux-headers-' + kernel_version
info.packages.add(kernel_headers_pkg)