Whitespace -> PEP-8

This commit is contained in:
Stefano Rivera 2010-11-23 08:54:42 +02:00
parent 04eb3ada8b
commit b78b21f43e

View File

@ -35,351 +35,363 @@ from sys import exit, argv, stderr
import ubuntutools.misc import ubuntutools.misc
debian_distros = ['etch', 'lenny', 'squeeze', 'sid', 'stable', \ debian_distros = ['etch', 'lenny', 'squeeze', 'sid', 'stable', 'testing',
'testing', 'unstable', 'experimental'] 'unstable', 'experimental']
class pbuilder_dist: class pbuilder_dist:
def __init__(self, builder): def __init__(self, builder):
# Base directory where pbuilder will put all the files it creates. # Base directory where pbuilder will put all the files it creates.
self.base = None self.base = None
# Name of the operation which pbuilder should perform. # Name of the operation which pbuilder should perform.
self.operation = None self.operation = None
# Wheter additional components should be used or not. That is, # Wheter additional components should be used or not. That is,
# 'universe' and 'multiverse' for Ubuntu chroots and 'contrib' # 'universe' and 'multiverse' for Ubuntu chroots and 'contrib'
# and 'non-free' for Debian. # and 'non-free' for Debian.
self.extra_components = True self.extra_components = True
# File where the log of the last operation will be saved. # File where the log of the last operation will be saved.
self.logfile = None self.logfile = None
# System architecture # System architecture
self.system_architecture = None self.system_architecture = None
# Build architecture # Build architecture
self.build_architecture = None self.build_architecture = None
# System's distribution # System's distribution
self.system_distro = None self.system_distro = None
# Target distribution # Target distribution
self.target_distro = None self.target_distro = None
# This is an identificative string which will either take the form # This is an identificative string which will either take the form
# 'distribution' or 'distribution-architecture'. # 'distribution' or 'distribution-architecture'.
self.chroot_string = None self.chroot_string = None
# Authentication method # Authentication method
self.auth = 'sudo' self.auth = 'sudo'
# Builder # Builder
self.builder = builder self.builder = builder
# Ensure that the used builder is installed # Ensure that the used builder is installed
paths = set(os.environ['PATH'].split(':')) paths = set(os.environ['PATH'].split(':'))
paths |= set(('/sbin', '/usr/sbin', '/usr/local/sbin')) paths |= set(('/sbin', '/usr/sbin', '/usr/local/sbin'))
if not any(os.path.exists(os.path.join(p, builder)) for p in paths): if not any(os.path.exists(os.path.join(p, builder)) for p in paths):
print >> stderr, 'Error: Could not find "%s".' % builder print >> stderr, 'Error: Could not find "%s".' % builder
exit(1) exit(1)
############################################################## ##############################################################
self.base = os.path.expanduser(os.environ.get('PBUILDFOLDER', '~/pbuilder/')) self.base = os.path.expanduser(os.environ.get('PBUILDFOLDER',
'~/pbuilder/'))
if not os.path.isdir(self.base): if not os.path.isdir(self.base):
try: try:
os.makedirs(self.base) os.makedirs(self.base)
except os.OSError: except os.OSError:
print >> stderr, ('Error: Cannot create base directory "%s"' print >> stderr, ('Error: Cannot create base directory "%s"'
% self.base) % self.base)
exit(1) exit(1)
if 'PBUILDAUTH' in os.environ: if 'PBUILDAUTH' in os.environ:
self.auth = os.environ['PBUILDAUTH'] self.auth = os.environ['PBUILDAUTH']
self.system_architecture = ubuntutools.misc.host_architecture() self.system_architecture = ubuntutools.misc.host_architecture()
self.system_distro = ubuntutools.misc.system_distribution() self.system_distro = ubuntutools.misc.system_distribution()
if not self.system_architecture or not self.system_distro: if not self.system_architecture or not self.system_distro:
exit(1) exit(1)
self.target_distro = self.system_distro self.target_distro = self.system_distro
############################################################## ##############################################################
def set_target_distro(self, distro): def set_target_distro(self, distro):
""" pbuilder_dist.set_target_distro(distro) -> None """ pbuilder_dist.set_target_distro(distro) -> None
Check if the given target distribution name is correct, if it Check if the given target distribution name is correct, if it
isn't know to the system ask the user for confirmation before isn't know to the system ask the user for confirmation before
proceeding, and finally either save the value into the appropiate proceeding, and finally either save the value into the appropiate
variable or finalize pbuilder-dist's execution. variable or finalize pbuilder-dist's execution.
""" """
if not distro.isalpha(): if not distro.isalpha():
print >> stderr, ('Error: "%s" is an invalid distribution codename.' print >> stderr, ('Error: "%s" is an invalid distribution codename.'
% distro) % distro)
exit(1) exit(1)
if not os.path.isfile(os.path.join('/usr/share/debootstrap/scripts/', distro)): if not os.path.isfile(os.path.join('/usr/share/debootstrap/scripts/',
if os.path.isdir('/usr/share/debootstrap/scripts/'): distro)):
# Debian experimental doesn't have a debootstrap file but if os.path.isdir('/usr/share/debootstrap/scripts/'):
# should work nevertheless. # Debian experimental doesn't have a debootstrap file but
if distro not in debian_distros: # should work nevertheless.
answer = ask('Warning: Unknown distribution "%s". Do you ' \ if distro not in debian_distros:
'want to continue [y/N]? ' % distro) answer = ask(('Warning: Unknown distribution "%s". Do you '
if answer not in ('y', 'Y'): 'want to continue [y/N]? ') % distro)
exit(0) if answer not in ('y', 'Y'):
else: exit(0)
print >> stderr, 'Please install package "debootstrap".' else:
exit(1) print >> stderr, 'Please install package "debootstrap".'
exit(1)
self.target_distro = distro self.target_distro = distro
def set_operation(self, operation): def set_operation(self, operation):
""" pbuilder_dist.set_operation -> None """ pbuilder_dist.set_operation -> None
Check if the given string is a valid pbuilder operation and Check if the given string is a valid pbuilder operation and
depending on this either save it into the appropiate variable depending on this either save it into the appropiate variable
or finalize pbuilder-dist's execution. or finalize pbuilder-dist's execution.
""" """
arguments = ('create', 'update', 'build', 'clean', 'login', 'execute') arguments = ('create', 'update', 'build', 'clean', 'login', 'execute')
if operation not in arguments: if operation not in arguments:
if operation.endswith('.dsc'): if operation.endswith('.dsc'):
if os.path.isfile(operation): if os.path.isfile(operation):
self.operation = 'build' self.operation = 'build'
return [operation] return [operation]
else: else:
print >> stderr, 'Error: Could not find file "%s".' % operation print >> stderr, ('Error: Could not find file "%s".'
exit(1) % operation)
else: exit(1)
print >> stderr, 'Error: "%s" is not a recognized argument.' % operation else:
print >> stderr, 'Please use one of these: %s.' % ', '.join(arguments) print >> stderr, (
exit(1) 'Error: "%s" is not a recognized argument.\n'
else: 'Please use one of these: %s.'
self.operation = operation ) % (operation, ', '.join(arguments))
return [] exit(1)
else:
self.operation = operation
return []
def get_command(self, remaining_arguments = None): def get_command(self, remaining_arguments = None):
""" pbuilder_dist.get_command -> string """ pbuilder_dist.get_command -> string
Generate the pbuilder command which matches the given configuration Generate the pbuilder command which matches the given configuration
and return it as a string. and return it as a string.
""" """
if not self.build_architecture: if not self.build_architecture:
self.chroot_string = self.target_distro self.chroot_string = self.target_distro
self.build_architecture = self.system_architecture self.build_architecture = self.system_architecture
else: else:
self.chroot_string = self.target_distro + '-' + self.build_architecture self.chroot_string = (self.target_distro + '-'
+ self.build_architecture)
prefix = os.path.join(self.base, self.chroot_string) prefix = os.path.join(self.base, self.chroot_string)
result = '%s_result/' % prefix result = '%s_result/' % prefix
if not self.logfile and self.operation != 'login': if not self.logfile and self.operation != 'login':
self.logfile = os.path.normpath('%s/last_operation.log' % result) self.logfile = os.path.normpath('%s/last_operation.log' % result)
if not os.path.isdir(result): if not os.path.isdir(result):
try: try:
os.makedirs(result) os.makedirs(result)
except os.OSError: except os.OSError:
print >> stderr, ('Error: Cannot create results directory "%s"' print >> stderr, ('Error: Cannot create results directory "%s"'
% result) % result)
exit(1) exit(1)
if self.builder == 'pbuilder': if self.builder == 'pbuilder':
base = '--basetgz "%s-base.tgz"' % prefix base = '--basetgz "%s-base.tgz"' % prefix
elif self.builder == 'cowbuilder': elif self.builder == 'cowbuilder':
base = '--basepath "%s-base.cow"' % prefix base = '--basepath "%s-base.cow"' % prefix
else: else:
print >> stderr, 'Error: Unrecognized builder "%s".' % self.builder print >> stderr, 'Error: Unrecognized builder "%s".' % self.builder
exit(1) exit(1)
arguments = [ arguments = [
'--%s' % self.operation, '--%s' % self.operation,
base, base,
'--distribution', self.target_distro, '--distribution', self.target_distro,
'--buildresult', result, '--buildresult', result,
'--aptcache', '/var/cache/apt/archives/', '--aptcache', '/var/cache/apt/archives/',
'--override-config', '--override-config',
] ]
if self.logfile: if self.logfile:
arguments += ['--logfile', self.logfile] arguments += ['--logfile', self.logfile]
if os.path.exists('/var/cache/archive/'): if os.path.exists('/var/cache/archive/'):
arguments += ['--bindmounts', '/var/cache/archive/'] arguments += ['--bindmounts', '/var/cache/archive/']
localrepo = '/var/cache/archive/' + self.target_distro localrepo = '/var/cache/archive/' + self.target_distro
if os.path.exists(localrepo): if os.path.exists(localrepo):
arguments += [ arguments += [
'--othermirror ', '--othermirror ',
'deb file:///var/cache/archive/ %s/' % self.target_distro, 'deb file:///var/cache/archive/ %s/' % self.target_distro,
] ]
if self.target_distro in debian_distros: if self.target_distro in debian_distros:
arguments += ['--mirror', 'http://ftp.debian.org/debian'] arguments += ['--mirror', 'http://ftp.debian.org/debian']
# work around bug #599695 # work around bug #599695
arguments += [ arguments += [
'--debootstrapopts', '--debootstrapopts',
'--keyring=/usr/share/keyrings/debian-archive-keyring.gpg', '--keyring=/usr/share/keyrings/debian-archive-keyring.gpg',
] ]
components = 'main' components = 'main'
if self.extra_components: if self.extra_components:
components += ' contrib non-free' components += ' contrib non-free'
else: else:
if self.build_architecture in ('amd64', 'i386'): if self.build_architecture in ('amd64', 'i386'):
arguments += ['--mirror', 'http://archive.ubuntu.com/ubuntu/'] arguments += ['--mirror', 'http://archive.ubuntu.com/ubuntu/']
elif self.build_architecture == 'powerpc' and self.target_distro == 'dapper': elif (self.build_architecture == 'powerpc'
arguments += ['--mirror', 'http://archive.ubuntu.com/ubuntu/'] and self.target_distro == 'dapper'):
else: arguments += ['--mirror', 'http://archive.ubuntu.com/ubuntu/']
arguments += ['--mirror', else:
'http://ports.ubuntu.com/ubuntu-ports/'] arguments += ['--mirror',
components = 'main restricted' 'http://ports.ubuntu.com/ubuntu-ports/']
if self.extra_components: components = 'main restricted'
components += ' universe multiverse' if self.extra_components:
components += ' universe multiverse'
arguments += ['--components', components] arguments += ['--components', components]
if self.build_architecture != self.system_architecture: if self.build_architecture != self.system_architecture:
arguments += ['--debootstrapopts', arguments += ['--debootstrapopts',
'--arch=' + self.build_architecture] '--arch=' + self.build_architecture]
apt_conf_dir = os.path.join(self.base, 'etc/%s/apt.conf' % self.target_distro) apt_conf_dir = os.path.join(self.base,
if os.path.exists(apt_conf_dir): 'etc/%s/apt.conf' % self.target_distro)
arguments += ['--aptconfdir', apt_conf_dir] if os.path.exists(apt_conf_dir):
arguments += ['--aptconfdir', apt_conf_dir]
# Append remaining arguments # Append remaining arguments
if remaining_arguments: if remaining_arguments:
arguments.extend(remaining_arguments) arguments.extend(remaining_arguments)
# Export the distribution and architecture information to the # Export the distribution and architecture information to the
# environment so that it is accessible to ~/.pbuilderrc (LP: #628933). # environment so that it is accessible to ~/.pbuilderrc (LP: #628933).
return [ return [
self.auth, self.auth,
'ARCH=' + self.build_architecture, 'ARCH=' + self.build_architecture,
'DIST=' + self.target_distro, 'DIST=' + self.target_distro,
self.builder, self.builder,
] + arguments ] + arguments
def ask(question): def ask(question):
""" ask(question) -> string """ ask(question) -> string
Ask the given question and return the answer. Also catch Ask the given question and return the answer. Also catch
KeyboardInterrupt (Ctrl+C) and EOFError (Ctrl+D) exceptions and KeyboardInterrupt (Ctrl+C) and EOFError (Ctrl+D) exceptions and
immediately return None if one of those is found. immediately return None if one of those is found.
""" """
try: try:
answer = raw_input(question) answer = raw_input(question)
except (KeyboardInterrupt, EOFError): except (KeyboardInterrupt, EOFError):
print print
answer = None answer = None
return answer return answer
def help(exit_code = 0): def help(exit_code = 0):
""" help() -> None """ help() -> None
Print a help message for pbuilder-dist, and exit with the given code. Print a help message for pbuilder-dist, and exit with the given code.
""" """
print 'See man pbuilder-dist for more information.' print 'See man pbuilder-dist for more information.'
exit(exit_code) exit(exit_code)
def main(): def main():
""" main() -> None """ main() -> None
This is pbuilder-dist's main function. It creates a pbuilder_dist This is pbuilder-dist's main function. It creates a pbuilder_dist
object, modifies all necessary settings taking data from the object, modifies all necessary settings taking data from the
executable's name and command line options and finally either ends executable's name and command line options and finally either ends
the script and runs pbuilder itself or exists with an error message. the script and runs pbuilder itself or exists with an error message.
""" """
script_name = os.path.basename(argv[0]) script_name = os.path.basename(argv[0])
parts = script_name.split('-') parts = script_name.split('-')
# Copy arguments into another list for save manipulation # Copy arguments into another list for save manipulation
args = argv[1:] args = argv[1:]
if '-' in script_name and (parts[0] != 'pbuilder' and \ if ('-' in script_name and parts[0] not in ('pbuilder', 'cowbuilder')
parts[0] != 'cowbuilder') or len(parts) > 3: or len(parts) > 3):
print >> stderr, 'Error: "%s" is not a valid name for a "pbuilder-dist" executable.' % script_name print >> stderr, ('Error: "%s" is not a valid name for a '
exit(1) '"pbuilder-dist" executable.') % script_name
exit(1)
if len(args) < 1: if len(args) < 1:
print >> stderr, 'Insufficient number of arguments.' print >> stderr, 'Insufficient number of arguments.'
help(1) help(1)
if args[0] in ('-h', '--help', 'help'): if args[0] in ('-h', '--help', 'help'):
help(0) help(0)
app = pbuilder_dist(parts[0]) app = pbuilder_dist(parts[0])
if len(parts) > 1 and parts[1] != 'dist' and '.' not in parts[1]: if len(parts) > 1 and parts[1] != 'dist' and '.' not in parts[1]:
app.set_target_distro(parts[1]) app.set_target_distro(parts[1])
else: else:
app.set_target_distro(args.pop(0)) app.set_target_distro(args.pop(0))
if len(parts) > 2: if len(parts) > 2:
requested_arch = parts[2] requested_arch = parts[2]
elif len(args) > 0 and args[0] in ("alpha", "amd64", "arm", "armeb", elif len(args) > 0 and args[0] in (
"armel", "i386", "lpia", "m68k", "mips", "mipsel", "powerpc", "ppc64", 'alpha', 'amd64', 'arm', 'armeb', 'armel', 'i386', 'lpia', 'm68k',
"sh4", "sh4eb", "sparc", "sparc64"): 'mips', 'mipsel', 'powerpc', 'ppc64', 'sh4', 'sh4eb', 'sparc',
requested_arch = args.pop(0) 'sparc64'):
else: requested_arch = args.pop(0)
requested_arch = None else:
requested_arch = None
if requested_arch: if requested_arch:
app.build_architecture = requested_arch app.build_architecture = requested_arch
# For some foreign architectures we need to use qemu # For some foreign architectures we need to use qemu
if requested_arch != app.system_architecture and (app.system_architecture, if (requested_arch != app.system_architecture
requested_arch) not in [("amd64", "i386"), ("amd64", "lpia"), and (app.system_architecture, requested_arch) not in [
("arm", "armel"), ("armel", "arm"), ("i386", "lpia"), ("lpia", "i386"), ('amd64', 'i386'), ('amd64', 'lpia'), ('arm', 'armel'),
("powerpc", "ppc64"), ("ppc64", "powerpc"), ("sparc", "sparc64"), ('armel', 'arm'), ('i386', 'lpia'), ('lpia', 'i386'),
("sparc64", "sparc")]: ('powerpc', 'ppc64'), ('ppc64', 'powerpc'),
args.append('--debootstrap qemu-debootstrap') ('sparc', 'sparc64'), ('sparc64', 'sparc')]):
args.append('--debootstrap qemu-debootstrap')
if 'mainonly' in argv or '--main-only' in argv: if 'mainonly' in argv or '--main-only' in argv:
app.extra_components = False app.extra_components = False
if 'mainonly' in argv: if 'mainonly' in argv:
args.remove('mainonly') args.remove('mainonly')
else: else:
args.remove('--main-only') args.remove('--main-only')
if len(args) < 1: if len(args) < 1:
print >> stderr, 'Insufficient number of arguments.' print >> stderr, 'Insufficient number of arguments.'
help(1) help(1)
# Parse the operation # Parse the operation
args = app.set_operation(args.pop(0)) + args args = app.set_operation(args.pop(0)) + args
if app.operation == 'build' and not '.dsc' in ' '.join(args): if app.operation == 'build' and not '.dsc' in ' '.join(args):
print >> stderr, 'Error: You have to specify a .dsc file if you want to build.' print >> stderr, ('Error: You have to specify a .dsc file if you want '
exit(1) 'to build.')
exit(1)
# Execute the pbuilder command # Execute the pbuilder command
if not '--debug-echo' in args: if not '--debug-echo' in args:
p = subprocess.Popen(app.get_command(args)) p = subprocess.Popen(app.get_command(args)))
exit(p.wait()) exit(p.wait())
else: else:
print app.get_command([arg for arg in args if arg != '--debug-echo']) print app.get_command([arg for arg in args if arg != '--debug-echo'])
if __name__ == '__main__': if __name__ == '__main__':
try: try:
main() main()
except KeyboardInterrupt: except KeyboardInterrupt:
print >> stderr, 'Manually aborted.' print >> stderr, 'Manually aborted.'
exit(1) exit(1)