Pylinting
authorEd Bartosh <eduard.bartosh@intel.com>
Mon, 25 Jun 2012 17:29:19 +0000 (20:29 +0300)
committerEd Bartosh <eduard.bartosh@intel.com>
Wed, 27 Jun 2012 09:01:11 +0000 (12:01 +0300)
Change-Id: Icf8b108ab7a799391d9bf4eb65fe9d341c05e4de

gitbuildsys/cmd_build.py
gitbuildsys/cmd_changelog.py
gitbuildsys/cmd_remotebuild.py
gitbuildsys/cmd_submit.py
gitbuildsys/conf.py
gitbuildsys/errors.py
gitbuildsys/msger.py
gitbuildsys/runner.py

index 52274c1..ecb71a9 100644 (file)
@@ -148,7 +148,8 @@ def setup_qemu_emulator():
         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)
@@ -365,9 +366,9 @@ def do(opts, args):
             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.')
@@ -401,15 +402,14 @@ def do(opts, args):
     # 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')
index ad3cf59..5051f8e 100644 (file)
@@ -162,7 +162,7 @@ def do(opts, _args):
             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")
 
index d42eb0e..75ada09 100644 (file)
@@ -124,7 +124,8 @@ def do(opts, args):
     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)
@@ -150,9 +151,9 @@ def do(opts, args):
     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')
index cbe6a7c..0a68e05 100644 (file)
@@ -63,10 +63,9 @@ def do(opts, args):
     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)
 
index f9b4c02..8dc99a3 100644 (file)
 # 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
 
@@ -42,7 +45,7 @@ class BrainConfigParser(SafeConfigParser):
 
         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
@@ -57,8 +60,8 @@ class BrainConfigParser(SafeConfigParser):
 
         # 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 = {}
@@ -67,9 +70,9 @@ class BrainConfigParser(SafeConfigParser):
         cursect = None
         optname = None
         lineno = 0
-        e = None
+        exc = ''
         while True:
-            line = fp.readline()
+            line = fptr.readline()
             if not line:
                 break
             lineno = lineno + 1
@@ -89,9 +92,9 @@ class BrainConfigParser(SafeConfigParser):
             # 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:
@@ -114,10 +117,11 @@ class BrainConfigParser(SafeConfigParser):
 
                 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(';')
@@ -137,13 +141,13 @@ class BrainConfigParser(SafeConfigParser):
                         # 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,
@@ -168,7 +172,7 @@ class BrainConfigParser(SafeConfigParser):
             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)
@@ -177,15 +181,15 @@ class BrainConfigParser(SafeConfigParser):
             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
@@ -198,9 +202,9 @@ class BrainConfigParser(SafeConfigParser):
 
         # 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"""
@@ -208,11 +212,11 @@ class BrainConfigParser(SafeConfigParser):
         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 = {
@@ -233,7 +237,7 @@ class ConfigMgr(object):
             },
     }
 
-    DEFAULT_CONF_TEMPLATE="""[general]
+    DEFAULT_CONF_TEMPLATE = """[general]
 ; general settings
 tmpdir = $general__tmpdir
 editor = $general__editor
@@ -298,12 +302,12 @@ distconf = $build__distconf
         """
 
         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
 
@@ -328,14 +332,15 @@ distconf = $build__distconf
 
             # 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)
index ea6b8e8..d3336cb 100644 (file)
@@ -20,29 +20,19 @@ class CmdError(Exception):
     """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>'
 
@@ -58,12 +48,5 @@ class QemuError(CmdError):
 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>'
index 03c6d19..cd6ef23 100644 (file)
@@ -180,7 +180,7 @@ class PrintBufWrapper(object):
             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
@@ -201,7 +201,6 @@ def _general_print(head, color, msg = None, stream = None, level = 'normal'):
             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'
@@ -211,7 +210,7 @@ def _general_print(head, color, msg = None, stream = None, level = 'normal'):
 
     _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 \
@@ -225,7 +224,7 @@ def _color_print(head, color, msg, stream, level):
         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
@@ -244,8 +243,6 @@ def _color_print(head, color, msg, stream, level):
     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:
@@ -265,15 +262,15 @@ def _split_msg(head, msg):
         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
@@ -317,14 +314,15 @@ def error(msg):
     _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
 
@@ -357,7 +355,7 @@ def waiting(f):
         timer.start()
 
         try:
-            out = f(*args, **kwargs)
+            out = func(*args, **kwargs)
         except:
             raise
         finally:
@@ -412,9 +410,9 @@ def set_logfile(fpath):
         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')
index f1a8124..fd8082e 100644 (file)
@@ -17,7 +17,7 @@
 # Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 
 import os
-from subprocess import *
+import subprocess
 
 import msger
 
@@ -53,22 +53,23 @@ def runtool(cmdln_or_args, catch=1):
         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:
@@ -77,12 +78,12 @@ def runtool(cmdln_or_args, catch=1):
         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)
@@ -99,7 +100,7 @@ def show(cmdln_or_args):
         msg += '\n  +----------------'
 
     msger.verbose(msg)
-    return rc
+    return rcode
 
 def outs(cmdln_or_args, catch=1):
     # get the outputs of tools
@@ -118,9 +119,9 @@ def embed(cmdln_or_args):
         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: