qemu_arm_string = ":arm:M::\\x7fELF\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x28\\x00:\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfa\\xff\\xff\\xff:%s:" % qemu_emulator
try:
(tmpfd, tmppth) = tempfile.mkstemp()
- os.write(tmpfd, "echo '%s' > /proc/sys/fs/binfmt_misc/register" % qemu_arm_string)
+ os.write(tmpfd, "echo '%s' > /proc/sys/fs/binfmt_misc/register" \
+ % qemu_arm_string)
os.close(tmpfd)
# on this way can work to use sudo register qemu emulator
ret = os.system('sudo sh %s' % tmppth)
msger.error('%s' % exc)
try:
- spec = rpm.parse_spec(specfile)
+ spec = rpm.parse_spec(specfile)
except GbpError, err:
- msger.error('%s' % err)
+ msger.error('%s' % err)
if not spec.name or not spec.version:
msger.error('can\'t get correct name or version from spec file.')
# runner.show() can't support interactive mode, so use subprocess insterad.
msger.debug("running command %s" % cmd)
try:
- rc = subprocess.call(cmd)
- if rc:
+ if subprocess.call(cmd):
msger.error('rpmbuild fails')
else:
msger.info('The buildroot was: %s' % build_root)
msger.info('Binaries RPM packges can be found here:\n %s/%s' % \
(build_root, 'home/abuild/rpmbuild/RPMS/'))
msger.info('Done')
- except KeyboardInterrupt, i:
+ except KeyboardInterrupt:
msger.info('keyboard interrupt, killing build ...')
subprocess.call(cmd + ["--kill"])
msger.error('interrrupt from keyboard')
shutil.copy2(temp.name, fn_changes)
except (IOError, shutil.Error), excobj:
msger.error("Can't update %s: %s" % (fn_changes, str(excobj)))
- msger.info("Change log has been updated.")
+ msger.info("Change log has been updated.")
else:
msger.info("Change log has not been updated")
target_prj_path = os.path.join(tmpdir, target_prj)
if os.path.exists(target_prj_path) and \
not os.access(target_prj_path, os.W_OK|os.R_OK|os.X_OK):
- msger.error('No access permission to %s, please check' % target_prj_path)
+ msger.error('No access permission to %s, please check' \
+ % target_prj_path)
localpkg = obspkg.ObsPackage(tmpdir, target_prj, spec.name,
APISERVER, oscrcpath)
try:
msger.info('commit packaging files to build server ...')
localpkg.commit ('submit packaging files to obs for OBS building')
- except errors.ObsError, e:
+ except errors.ObsError, exc:
msger.error('commit packages fail: %s, please check the permission '\
- 'of target project:%s' % (e,target_prj))
+ 'of target project:%s' % (exc,target_prj))
os.unlink(oscrcpath)
msger.info('local changes submitted to build server successfully')
if not os.path.exists(changesfile):
msger.error('No changelog file, so not be allowed to submit')
- file_list = []
changelog_file = changesfile.replace('%s/' % workdir, '')
try:
- changelog_status= repo.status([changelog_file])
+ changelog_status = repo.status([changelog_file])
except GbpError, err:
msger.error('failed to get the status of change log file: %s' % err)
# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
from __future__ import with_statement
-import os, sys
+import os
import base64
from collections import defaultdict
-from ConfigParser import *
+from ConfigParser import SafeConfigParser, DEFAULTSECT, ParsingError, \
+ NoSectionError, NoOptionError, \
+ MissingSectionHeaderError
+
import msger
import errors
return SafeConfigParser.read(self, filenames)
- def _read(self, fp, fname):
+ def _read(self, fptr, fname):
"""Parse a sectioned setup file.
Override the same method of parent class. Some code snip were
# save the original filepath and contents
self._fpname = fname
- self._flines = fp.readlines()
- fp.seek(0)
+ self._flines = fptr.readlines()
+ fptr.seek(0)
# init dict DS to store lineno
self._sec_linenos = {}
cursect = None
optname = None
lineno = 0
- e = None
+ exc = ''
while True:
- line = fp.readline()
+ line = fptr.readline()
if not line:
break
lineno = lineno + 1
# a section header or option header?
else:
# is it a section header?
- mo = self.SECTCRE.match(line)
- if mo:
- sectname = mo.group('header')
+ match = self.SECTCRE.match(line)
+ if match:
+ sectname = match.group('header')
if sectname in self._sec_linenos:
self._sec_linenos[sectname].append(lineno)
else:
else:
# an option line?
- mo = self.OPTCRE.match(line)
- if mo:
- optname, vi, optval = mo.group('option', 'vi', 'value')
- if vi in ('=', ':') and ';' in optval:
+ match = self.OPTCRE.match(line)
+ if match:
+ optname, sign, optval = match.group('option',
+ 'vi', 'value')
+ if sign in ('=', ':') and ';' in optval:
# ';' is a comment delimiter only if it follows
# a spacing character
pos = optval.find(';')
# exception but keep going. the exception will be
# raised at the end of the file and will contain a
# list of all bogus lines
- if not e:
- e = ParsingError(fname)
- e.append(lineno, repr(line))
+ if not exc:
+ exc = ParsingError(fname)
+ exc.append(lineno, repr(line))
# if any parsing errors occurred, raise an exception
- if e:
- raise e
+ if exc:
+ raise exc
def set(self, section, option, value, replace_opt=None):
"""When set new value, need to update the readin file lines,
return -1
SafeConfigParser.set(self, section, option, value)
-
+
# If the code reach here, it means the section and key are ok
if replace_opt is None:
o_kname = "%s.%s" % (section, option)
o_kname = "%s.%s" % (section, option)
n_kname = "%s.%s" % (section, replace_opt)
- line = '%s = %s\n' %(option, value)
+ line = '%s = %s\n' % (option, value)
if n_kname in self._opt_linenos:
# update an old key
self._flines[self._opt_linenos[n_kname][0]-1] = line
if len(self._opt_linenos[n_kname]) > 1:
# multiple lines value, remote the rest
- for ln in range(self._opt_linenos[n_kname][1]-1,
- self._opt_linenos[n_kname][-1]):
- self._flines[ln] = None
+ for lno in range(self._opt_linenos[n_kname][1]-1,
+ self._opt_linenos[n_kname][-1]):
+ self._flines[lno] = None
else:
# new key
line += '\n' # one more blank line
# remove old opt if need
if o_kname != n_kname and o_kname in self._opt_linenos:
- for ln in range(self._opt_linenos[o_kname][0]-1,
- self._opt_linenos[o_kname][-1]):
- self._flines[ln] = None
+ for lno in range(self._opt_linenos[o_kname][0]-1,
+ self._opt_linenos[o_kname][-1]):
+ self._flines[lno] = None
def update(self):
"""Update the original config file using updated values"""
if self._fpname == '<???>':
return
- fp = open(self._fpname, 'w')
+ fptr = open(self._fpname, 'w')
for line in self._flines:
if line is not None:
- fp.write(line)
- fp.close()
+ fptr.write(line)
+ fptr.close()
class ConfigMgr(object):
DEFAULTS = {
},
}
- DEFAULT_CONF_TEMPLATE="""[general]
+ DEFAULT_CONF_TEMPLATE = """[general]
; general settings
tmpdir = $general__tmpdir
editor = $general__editor
"""
paths = []
- for p in ('/etc/gbs.conf',
- os.path.expanduser('~/.gbs.conf'),
- os.path.abspath('.gbs.conf'),
- os.path.abspath('.git/gbs.conf')):
- if os.path.exists(p) and p not in paths:
- paths.append(p)
+ for path in ('/etc/gbs.conf',
+ os.path.expanduser('~/.gbs.conf'),
+ os.path.abspath('.gbs.conf'),
+ os.path.abspath('.git/gbs.conf')):
+ if os.path.exists(path) and path not in paths:
+ paths.append(path)
return paths
# user and passwd in [build] section need user input
defaults = self.DEFAULTS.copy()
- defaults['remotebuild']['user'] = raw_input('Username for remote build server: ')
+ defaults['remotebuild']['user'] = \
+ raw_input('Username for remote build server: ')
msger.info('Your password will be encoded before saving ...')
defaults['remotebuild']['passwd'] = ''
defaults['remotebuild']['passwdx'] = \
base64.b64encode(getpass.getpass().encode('bz2'))
- with open(fpath, 'w') as wf:
- wf.write(self.get_default_conf(defaults))
+ with open(fpath, 'w') as wfile:
+ wfile.write(self.get_default_conf(defaults))
os.chmod(fpath, 0600)
msger.info('Done. Your gbs config is now located at %s' % fpath)
"""An exception base class for all command calling errors."""
keyword = ''
- def __init__(self, msg):
- self.msg = msg
-
def __str__(self):
- return self.keyword + str(self.msg)
+ return self.keyword + str(self.args[0])
class Usage(CmdError):
keyword = '<usage>'
def __str__(self):
- return self.keyword + str(self.msg) + \
+ return self.keyword + str(self.args[0]) + \
', please use "--help" for more info'
class ConfigError(CmdError):
keyword = '<config>'
-class GitError(CmdError):
- keyword = '<git>'
-
-class GitInvalid(GitError):
- def __str__(self):
- return '<git>dir %s is not a valid git tree' % str(self.msg)
-
class ObsError(CmdError):
keyword = '<obs>'
class Abort(CmdError):
keyword = ''
-class GBSError(Exception):
-
- def __init__(self, msg):
- self.msg = msg
-
- def __str__(self):
- return self.msg
class UrlError(CmdError):
keyword = '<urlgrab>'
return orig_attr
def _general_print(head, color, msg = None, stream = None, level = 'normal'):
- global LOG_CONTENT, STDOUT
+ global LOG_CONTENT
if LOG_LEVELS[level] > LOG_LEVEL:
# skip
LOG_CONTENT += errormsg
if msg and msg.strip():
- global HOST_TIMEZONE
timestr = time.strftime("[%m/%d %H:%M:%S] ",
time.gmtime(time.time() - HOST_TIMEZONE))
LOG_CONTENT += timestr + msg.strip() + '\n'
_color_print(head, color, msg, stream, level)
-def _color_print(head, color, msg, stream, level):
+def _color_print(head, color, msg, stream, _level):
colored = True
if color == NO_COLOR or \
not stream.isatty() or \
newline = True
if colored:
- head = '\033[%dm%s:\033[0m ' %(color, head)
+ head = '\033[%dm%s:\033[0m ' % (color, head)
if not newline:
# ESC cmd to clear line
head = '\033[2K' + head
stream.flush()
def _color_perror(head, color, msg, level = 'normal'):
- global STDOUT, STDERR
-
if CATCHERR_BUFFILE_FD > 0:
_general_print(head, color, msg, STDOUT, level)
else:
msg = msg.lstrip()
head = '\r' + head
- m = PREFIX_RE.match(msg)
- if m:
- head += ' <%s>' % m.group(1)
- msg = m.group(2)
+ match = PREFIX_RE.match(msg)
+ if match:
+ head += ' <%s>' % match.group(1)
+ msg = match.group(2)
return head, msg
def get_loglevel():
- return (k for k,v in LOG_LEVELS.items() if v==LOG_LEVEL).next()
+ return (k for k, v in LOG_LEVELS.items() if v==LOG_LEVEL).next()
def set_loglevel(level):
global LOG_LEVEL
_color_perror(head, ERR_COLOR, msg)
sys.exit(1)
-def waiting(f):
- """Function decorator to show simple waiting message for
+def waiting(func):
+ """
+ Function decorator to show simple waiting message for
long time operations.
"""
import functools
- @functools.wraps(f)
+ @functools.wraps(func)
def _wait_with_print(*args, **kwargs):
import threading
timer.start()
try:
- out = f(*args, **kwargs)
+ out = func(*args, **kwargs)
except:
raise
finally:
if LOG_FILE_FP:
if not os.path.exists(os.path.dirname(LOG_FILE_FP)):
os.makedirs(os.path.dirname(LOG_FILE_FP))
- fp = open(LOG_FILE_FP, 'w')
- fp.write(LOG_CONTENT)
- fp.close()
+ fhandle = open(LOG_FILE_FP, 'w')
+ fhandle.write(LOG_CONTENT)
+ fhandle.close()
if LOG_FILE_FP is not None:
warning('duplicate log file configuration')
# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
import os
-from subprocess import *
+import subprocess
import msger
sout = dev_null
serr = dev_null
elif catch == 1:
- sout = PIPE
+ sout = subprocess.PIPE
serr = dev_null
elif catch == 2:
sout = dev_null
- serr = PIPE
+ serr = subprocess.PIPE
elif catch == 3:
- sout = PIPE
- serr = STDOUT
+ sout = subprocess.PIPE
+ serr = subprocess.STDOUT
try:
- p = Popen(cmdln_or_args, stdout=sout, stderr=serr, shell=shell)
- out = p.communicate()[0]
+ process = subprocess.Popen(cmdln_or_args, stdout=sout,
+ stderr=serr, shell=shell)
+ out = process.communicate()[0]
if out is None:
out = ''
- except OSError, e:
- if e.errno == 2:
+ except OSError, exc:
+ if exc.errno == 2:
# [Errno 2] No such file or directory
msger.error('Cannot run command: %s, lost dependency?' % cmd)
else:
if catch != 3:
os.close(dev_null)
- return (p.returncode, out)
+ return (process.returncode, out)
def show(cmdln_or_args):
# show all the message using msger.verbose
- rc, out = runtool(cmdln_or_args, catch=3)
+ rcode, out = runtool(cmdln_or_args, catch=3)
if isinstance(cmdln_or_args, list):
cmd = ' '.join(cmdln_or_args)
msg += '\n +----------------'
msger.verbose(msg)
- return rc
+ return rcode
def outs(cmdln_or_args, catch=1):
# get the outputs of tools
args = shlex.split(cmdln_or_args)
try:
- sts = call(args)
- except OSError, e:
- if e.errno == 2:
+ sts = subprocess.call(args)
+ except OSError, exc:
+ if exc.errno == 2:
# [Errno 2] No such file or directory
msger.error('Cannot run command: %s, lost dependency?' % args[0])
else: