Don't redefine variables from outer scope

This commit is contained in:
Alexander Todorov 2017-10-12 15:55:55 +03:00 committed by Brian C. Lane
parent 4d8e2b5356
commit a0766b1d70
9 changed files with 46 additions and 37 deletions

View File

@ -32,8 +32,8 @@ class ImageMinimizer:
drops_rpm = set() drops_rpm = set()
ts = None ts = None
def __init__(self, filename, root, dryrun, verbose): def __init__(self, _filename, root, dryrun, verbose):
self.filename = filename self.filename = _filename
self.prefix = root self.prefix = root
self.dryrun = dryrun self.dryrun = dryrun
self.verbose = verbose self.verbose = verbose
@ -173,12 +173,12 @@ def parse_options():
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
help="Display every action as it is performed.") help="Display every action as it is performed.")
(options, args) = parser.parse_args() (_options, _args) = parser.parse_args()
if len(args) == 0: if len(args) == 0:
parser.print_help() parser.print_help()
sys.exit(1) sys.exit(1)
return (options, args) return (_options, _args)
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -51,8 +51,8 @@ def is_image_mounted(disk_img):
Return True if the disk_img is mounted Return True if the disk_img is mounted
""" """
with open("/proc/mounts") as mounts: with open("/proc/mounts") as mounts:
for mount in mounts: for _mount in mounts:
fields = mount.split() fields = _mount.split()
if len(fields) > 2 and fields[1] == disk_img: if len(fields) > 2 and fields[1] == disk_img:
return True return True
return False return False

View File

@ -233,24 +233,24 @@ def mount(dev, opts="", mnt=None):
if mnt is None: if mnt is None:
mnt = tempfile.mkdtemp(prefix="lorax.imgutils.") mnt = tempfile.mkdtemp(prefix="lorax.imgutils.")
logger.debug("make tmp mountdir %s", mnt) logger.debug("make tmp mountdir %s", mnt)
mount = ["mount"] cmd = ["mount"]
if opts: if opts:
mount += ["-o", opts] cmd += ["-o", opts]
mount += [dev, mnt] cmd += [dev, mnt]
runcmd(mount) runcmd(cmd)
return mnt return mnt
def umount(mnt, lazy=False, maxretry=3, retrysleep=1.0): def umount(mnt, lazy=False, maxretry=3, retrysleep=1.0):
'''Unmount the given mountpoint. If lazy is True, do a lazy umount (-l). '''Unmount the given mountpoint. If lazy is True, do a lazy umount (-l).
If the mount was a temporary dir created by mount, it will be deleted. If the mount was a temporary dir created by mount, it will be deleted.
raises CalledProcessError if umount fails.''' raises CalledProcessError if umount fails.'''
umount = ["umount"] cmd = ["umount"]
if lazy: umount += ["-l"] if lazy: cmd += ["-l"]
umount += [mnt] cmd += [mnt]
count = 0 count = 0
while maxretry > 0: while maxretry > 0:
try: try:
rv = runcmd(umount) rv = runcmd(cmd)
except CalledProcessError: except CalledProcessError:
count += 1 count += 1
if count == maxretry: if count == maxretry:
@ -335,7 +335,7 @@ class LoopDev(object):
def __enter__(self): def __enter__(self):
self.loopdev = loop_attach(self.filename) self.loopdev = loop_attach(self.filename)
return self.loopdev return self.loopdev
def __exit__(self, exc_type, exc_value, traceback): def __exit__(self, exc_type, exc_value, exc_tb):
loop_detach(self.loopdev) loop_detach(self.loopdev)
class DMDev(object): class DMDev(object):
@ -345,7 +345,7 @@ class DMDev(object):
def __enter__(self): def __enter__(self):
self.mapperdev = dm_attach(self.dev, self.size, self.name) self.mapperdev = dm_attach(self.dev, self.size, self.name)
return self.mapperdev return self.mapperdev
def __exit__(self, exc_type, exc_value, traceback): def __exit__(self, exc_type, exc_value, exc_tb):
dm_detach(self.mapperdev) dm_detach(self.mapperdev)
class Mount(object): class Mount(object):
@ -354,7 +354,7 @@ class Mount(object):
def __enter__(self): def __enter__(self):
self.mnt = mount(self.dev, self.opts, self.mnt) self.mnt = mount(self.dev, self.opts, self.mnt)
return self.mnt return self.mnt
def __exit__(self, exc_type, exc_value, traceback): def __exit__(self, exc_type, exc_value, exc_tb):
umount(self.mnt) umount(self.mnt)
class PartitionMount(object): class PartitionMount(object):
@ -412,7 +412,7 @@ class PartitionMount(object):
os.rmdir(mount_dir) os.rmdir(mount_dir)
return self return self
def __exit__(self, exc_type, exc_value, traceback): def __exit__(self, exc_type, exc_value, exc_tb):
if self.mount_dir: if self.mount_dir:
umount( self.mount_dir ) umount( self.mount_dir )
os.rmdir(self.mount_dir) os.rmdir(self.mount_dir)

View File

@ -147,11 +147,11 @@ class LoraxTemplateRunner(object):
* Commands should raise exceptions for errors - don't use sys.exit() * Commands should raise exceptions for errors - don't use sys.exit()
''' '''
def __init__(self, inroot, outroot, yum=None, fatalerrors=True, def __init__(self, inroot, outroot, yum_obj=None, fatalerrors=True,
templatedir=None, defaults={}): templatedir=None, defaults={}):
self.inroot = inroot self.inroot = inroot
self.outroot = outroot self.outroot = outroot
self.yum = yum self.yum = yum_obj
self.fatalerrors = fatalerrors self.fatalerrors = fatalerrors
self.templatedir = templatedir or "/usr/share/lorax" self.templatedir = templatedir or "/usr/share/lorax"
self.templatefile = None self.templatefile = None
@ -455,9 +455,9 @@ class LoraxTemplateRunner(object):
cmd = cmd[1:] cmd = cmd[1:]
try: try:
output = runcmd_output(cmd, cwd=cwd) _output = runcmd_output(cmd, cwd=cwd)
if output: if _output:
logger.debug('command output:\n%s', output) logger.debug('command output:\n%s', _output)
logger.debug("command finished successfully") logger.debug("command finished successfully")
except CalledProcessError as e: except CalledProcessError as e:
if e.output: if e.output:
@ -555,15 +555,15 @@ class LoraxTemplateRunner(object):
logger.debug("removefrom %s %s: no files matched!", pkg, g) logger.debug("removefrom %s %s: no files matched!", pkg, g)
# are we removing the matches, or keeping only the matches? # are we removing the matches, or keeping only the matches?
if keepmatches: if keepmatches:
remove = filelist.difference(matches) files_to_remove = filelist.difference(matches)
else: else:
remove = matches files_to_remove = matches
# remove the files # remove the files
if remove: if files_to_remove:
logger.debug("%s: removed %i/%i files, %ikb/%ikb", cmd, logger.debug("%s: removed %i/%i files, %ikb/%ikb", cmd,
len(remove), len(filelist), len(files_to_remove), len(filelist),
self._getsize(*remove)/1024, self._getsize(*filelist)/1024) self._getsize(*files_to_remove)/1024, self._getsize(*filelist)/1024)
self.remove(*remove) self.remove(*files_to_remove)
else: else:
logger.debug("removefrom %s: no files to remove!", cmd) logger.debug("removefrom %s: no files to remove!", cmd)

View File

@ -47,12 +47,12 @@ def touch(fname):
pass pass
def replace(fname, find, replace): def replace(fname, find, substitute):
fin = fileinput.input(fname, inplace=1) fin = fileinput.input(fname, inplace=1)
pattern = re.compile(find) pattern = re.compile(find)
for line in fin: for line in fin:
line = pattern.sub(replace, line) line = pattern.sub(substitute, line)
sys.stdout.write(line) sys.stdout.write(line)
fin.close() fin.close()

View File

@ -79,7 +79,7 @@ class RuntimeBuilder(object):
basearch=arch.basearch, libdir=arch.libdir) basearch=arch.basearch, libdir=arch.libdir)
self.yum = yum self.yum = yum
self._runner = LoraxTemplateRunner(inroot=root, outroot=root, self._runner = LoraxTemplateRunner(inroot=root, outroot=root,
_yum=yum, templatedir=templatedir) yum_obj=yum, templatedir=templatedir)
self.add_templates = add_templates or [] self.add_templates = add_templates or []
self.add_template_vars = add_template_vars or {} self.add_template_vars = add_template_vars or {}
self._installpkgs = installpkgs or [] self._installpkgs = installpkgs or []

View File

@ -239,7 +239,7 @@ def default_image_name(compression, basename):
return basename + SUFFIXES.get(compression, ".xz") return basename + SUFFIXES.get(compression, ".xz")
if __name__ == '__main__': def main():
# parse the arguments # parse the arguments
parser = lorax_parser() parser = lorax_parser()
opts = parser.parse_args() opts = parser.parse_args()
@ -390,8 +390,8 @@ if __name__ == '__main__':
"multiple partitions. swap is allowed but not used.") "multiple partitions. swap is allowed but not used.")
if errors: if errors:
for e in errors: for _e in errors:
log.error(e) log.error(_e)
sys.exit(1) sys.exit(1)
# Make the image. Output of this is either a partitioned disk image or a fsimage # Make the image. Output of this is either a partitioned disk image or a fsimage
@ -480,3 +480,6 @@ if __name__ == '__main__':
log.info("Results are in %s", opts.result_dir or result_dir) log.info("Results are in %s", opts.result_dir or result_dir)
sys.exit( 0 ) sys.exit( 0 )
if __name__ == '__main__':
main()

View File

@ -113,7 +113,7 @@ def mkefidisk(efiboot, outfile):
outfile.write(infile.read()) outfile.write(infile.read())
dm_detach(dmdev+"p1") dm_detach(dmdev+"p1")
if __name__ == '__main__': def main():
parser = argparse.ArgumentParser(description="Make an EFI boot image from the given directory.") parser = argparse.ArgumentParser(description="Make an EFI boot image from the given directory.")
parser.add_argument("--debug", action="store_const", const=logging.DEBUG, parser.add_argument("--debug", action="store_const", const=logging.DEBUG,
dest="loglevel", default=log.getEffectiveLevel(), dest="loglevel", default=log.getEffectiveLevel(),
@ -157,3 +157,6 @@ if __name__ == '__main__':
efiboot = tempfile.NamedTemporaryFile(prefix="mkefiboot.").name efiboot = tempfile.NamedTemporaryFile(prefix="mkefiboot.").name
shutil.move(opt.outfile, efiboot) shutil.move(opt.outfile, efiboot)
mkefidisk(efiboot, opt.outfile) mkefidisk(efiboot, opt.outfile)
if __name__ == '__main__':
main()

View File

@ -43,7 +43,7 @@ def readtemplate(templatefile):
lookup = TemplateLookup(directories=parser.directories) lookup = TemplateLookup(directories=parser.directories)
return lookup.get_template(templatefile) return lookup.get_template(templatefile)
if __name__ == '__main__': def main():
# check args # check args
if len(sys.argv) == 1: if len(sys.argv) == 1:
print "usage: %s TEMPLATE [arg1=value1] [arg2=value2] ..." print "usage: %s TEMPLATE [arg1=value1] [arg2=value2] ..."
@ -78,3 +78,6 @@ if __name__ == '__main__':
except Exception: except Exception:
print text_error_template().render() print text_error_template().render()
raise SystemExit(1) raise SystemExit(1)
if __name__ == '__main__':
main()