Py3k compatibility patch by Ali Polatel <hawking@g.o>.
authorZac Medico <zmedico@gentoo.org>
Wed, 2 Jul 2008 07:50:54 +0000 (07:50 -0000)
committerZac Medico <zmedico@gentoo.org>
Wed, 2 Jul 2008 07:50:54 +0000 (07:50 -0000)
Don't use the format raise Exception, "string"

svn path=/main/trunk/; revision=10890

DEVELOPING
pym/portage/__init__.py
pym/portage/checksum.py
pym/portage/dbapi/porttree.py
pym/portage/dep.py
pym/portage/getbinpkg.py
pym/portage/gpg.py
pym/portage/locks.py

index cd9f78f9460d95b5291c1ccfd20486ca41b125a7..8286a8bcf2967ff0e55ff950f95e98429b9d2625 100644 (file)
@@ -94,6 +94,18 @@ except KeyError:
 
 The get call is nicer (compact) and faster (try,except are slow).
 
+Exceptions
+----------
+
+Don't use the format raise Exception, "string"
+It will be removed in py3k.
+
+YES:
+  raise KeyError("No key")
+
+NO:
+  raise KeyError, "No key"
+
 Imports
 -------
 
index 06193e7177d501dc3c91d223321ec08082f88771..6cba85bf78b951fa3f154e4a010c4dd58dee54ab 100644 (file)
@@ -169,7 +169,7 @@ def best_from_dict(key, top_dict, key_order, EmptyOnError=1, FullCopy=1, AllowEm
        if EmptyOnError:
                return ""
        else:
-               raise KeyError, "Key not found in list; '%s'" % key
+               raise KeyError("Key not found in list; '%s'" % key)
 
 def getcwd():
        "this fixes situations where the current directory doesn't exist"
@@ -1804,14 +1804,14 @@ class config(object):
 
        def modifying(self):
                if self.locked:
-                       raise Exception, "Configuration is locked."
+                       raise Exception("Configuration is locked.")
 
        def backup_changes(self,key=None):
                self.modifying()
                if key and key in self.configdict["env"]:
                        self.backupenv[key] = copy.deepcopy(self.configdict["env"][key])
                else:
-                       raise KeyError, "No such key defined in environment: %s" % key
+                       raise KeyError("No such key defined in environment: %s" % key)
 
        def reset(self,keeping_pkg=0,use_cache=1):
                """
index 52ce59148f9d9b11139b48beecbf1b2895d26c92..8364d26edf39aa34000f80c64f2c4e9abf2d962e 100644 (file)
@@ -186,7 +186,10 @@ def verify_all(filename, mydict, calc_prelink=0, strict=0):
                        myhash = perform_checksum(filename, x, calc_prelink=calc_prelink)[0]
                        if mydict[x] != myhash:
                                if strict:
-                                       raise portage.exception.DigestException, "Failed to verify '$(file)s' on checksum type '%(type)s'" % {"file":filename, "type":x}
+                                       raise portage.exception.DigestException(
+                                               ("Failed to verify '$(file)s' on " + \
+                                               "checksum type '%(type)s'") % \
+                                               {"file" : filename, "type" : x})
                                else:
                                        file_is_ok = False
                                        reason     = (("Failed on %s verification" % x), myhash,mydict[x])
index e2a53aac4443375f02957ecdee3cea3460bef560..dd8015cc1c44e5ddab3b8e88ba3bd41fe691ada5 100644 (file)
@@ -263,11 +263,15 @@ class portdbapi(dbapi):
                                elif self.manifestVerifier:
                                        if not self.manifestVerifier.verify(myManifestPath):
                                                # Verification failed the desired level.
-                                               raise UntrustedSignature, "Untrusted Manifest: %(manifest)s" % {"manifest":myManifestPath}
+                                               raise UntrustedSignature(
+                                                       "Untrusted Manifest: %(manifest)s" % \
+                                                       {"manifest" : myManifestPath})
 
                                if ("severe" in self.mysettings.features) and \
                                   (mys != portage.gpg.fileStats(myManifestPath)):
-                                       raise SecurityViolation, "Manifest changed: %(manifest)s" % {"manifest":myManifestPath}
+                                       raise SecurityViolation(
+                                               "Manifest changed: %(manifest)s" % \
+                                               {"manifest":myManifestPath})
 
                        except InvalidSignature, e:
                                if ("strict" in self.mysettings.features) or \
@@ -284,7 +288,9 @@ class portdbapi(dbapi):
                        except (OSError, FileNotFound), e:
                                if ("strict" in self.mysettings.features) or \
                                   ("severe" in self.mysettings.features):
-                                       raise SecurityViolation, "Error in verification of signatures: %(errormsg)s" % {"errormsg":str(e)}
+                                       raise SecurityViolation(
+                                               "Error in verification of signatures: " + \
+                                               "%(errormsg)s" % {"errormsg" : str(e)})
                                writemsg("!!! Manifest is missing or inaccessable: %(manifest)s\n" % {"manifest":myManifestPath},
                                        noiselevel=-1)
 
index 41d6b128b939429d73e316dcb46e913811a13910..c2f506d4bd321181cfaa6a20fe5d63d48b4221d6 100644 (file)
@@ -246,7 +246,7 @@ def use_reduce(deparray, uselist=[], masklist=[], matchall=0, excludeall=[]):
                                        if mydeparray:
                                                newdeparray.append(mydeparray.pop(0))
                                        else:
-                                               raise ValueError, "Conditional with no target."
+                                               raise ValueError("Conditional with no target.")
 
                                # Deprecation checks
                                warned = 0
index 412d753df9c1ae55baf87c79d7c00eae4cbe7ea4..da0dd77ad3e85ea6389befc9a12ee477d4f2348b 100644 (file)
@@ -82,7 +82,8 @@ def create_conn(baseurl,conn=None):
 
        parts = baseurl.split("://",1)
        if len(parts) != 2:
-               raise ValueError, "Provided URL does not contain protocol identifier. '%s'" % baseurl
+               raise ValueError("Provided URL does not " + \
+                       "contain protocol identifier. '%s'" % baseurl)
        protocol,url_parts = parts
        del parts
 
@@ -104,7 +105,7 @@ def create_conn(baseurl,conn=None):
        del userpass_host
 
        if len(userpass) > 2:
-               raise ValueError, "Unable to interpret username/password provided."
+               raise ValueError("Unable to interpret username/password provided.")
        elif len(userpass) == 2:
                username = userpass[0]
                password = userpass[1]
@@ -323,7 +324,7 @@ def dir_get_list(baseurl,conn=None):
        elif protocol == "sftp":
                listing = conn.listdir(address)
        else:
-               raise TypeError, "Unknown protocol. '%s'" % protocol
+               raise TypeError("Unknown protocol. '%s'" % protocol)
 
        if not keepconnection:
                conn.close()
@@ -355,7 +356,7 @@ def file_get_metadata(baseurl,conn=None, chunk_size=3000):
                finally:
                        f.close()
        else:
-               raise TypeError, "Unknown protocol. '%s'" % protocol
+               raise TypeError("Unknown protocol. '%s'" % protocol)
        
        if data:
                xpaksize = portage.xpak.decodeint(data[-8:-4])
@@ -447,7 +448,7 @@ def file_get_lib(baseurl,dest,conn=None):
                        finally:
                                f.close()
        else:
-               raise TypeError, "Unknown protocol. '%s'" % protocol
+               raise TypeError("Unknown protocol. '%s'" % protocol)
        
        if not keepconnection:
                conn.close()
index 1fdac62529d3ad70e75af9bb82fb71e359f640e5..1ddb99d3ee4e4dfef19a1c4f75eb1c4555d0284f 100644 (file)
@@ -10,6 +10,10 @@ import types
 import commands
 import portage.exception
 import portage.checksum
+from portage.exception import CommandNotFound, \
+       DirectoryNotFound, FileNotFound, \
+       InvalidData, InvalidDataType, InvalidSignature, MissingParameter, \
+       MissingSignature, PortageException, SecurityViolation
 
 GPG_BINARY       = "/usr/bin/gpg"
 GPG_OPTIONS      = " --lock-never --no-random-seed-file --no-greeting --no-sig-cache "
@@ -42,34 +46,38 @@ class FileChecker(object):
                if (keydir != None):
                        # Verify that the keydir is valid.
                        if type(keydir) != types.StringType:
-                               raise portage.exception.InvalidDataType, "keydir argument: %s" % keydir
+                               raise InvalidDataType(
+                                       "keydir argument: %s" % keydir)
                        if not os.path.isdir(keydir):
-                               raise portage.exception.DirectoryNotFound, "keydir: %s" % keydir
+                               raise DirectoryNotFound("keydir: %s" % keydir)
                        self.keydir = copy.deepcopy(keydir)
 
                if (keyring != None):
                        # Verify that the keyring is a valid filename and exists.
                        if type(keyring) != types.StringType:
-                               raise portage.exception.InvalidDataType, "keyring argument: %s" % keyring
+                               raise InvalidDataType("keyring argument: %s" % keyring)
                        if keyring.find("/") != -1:
-                               raise portage.exception.InvalidData, "keyring: %s" % keyring
+                               raise InvalidData("keyring: %s" % keyring)
                        pathname = ""
                        if keydir:
                                pathname = keydir + "/" + keyring
                        if not os.path.isfile(pathname):
-                               raise portage.exception.FileNotFound, "keyring missing: %s (dev.gentoo.org/~carpaski/gpg/)" % pathname
+                               raise FileNotFound(
+                                       "keyring missing: %s (dev.gentoo.org/~carpaski/gpg/)" % \
+                                       pathname)
 
                keyringPath = keydir+"/"+keyring
 
                if not keyring or not keyringPath and requireSignedRing:
-                       raise portage.exception.MissingParameter
+                       raise MissingParameter((keyring, keyringPath))
 
                self.keyringStats = fileStats(keyringPath)
                self.minimumTrust = TRUSTED
                if not self.verify(keyringPath, keyringPath+".asc"):
                        self.keyringIsTrusted = False
                        if requireSignedRing:
-                               raise portage.exception.InvalidSignature, "Required keyring verification: "+keyringPath
+                               raise InvalidSignature(
+                                       "Required keyring verification: " + keyringPath)
                else:
                        self.keyringIsTrusted = True
                
@@ -81,27 +89,27 @@ class FileChecker(object):
                if self.keyringStats and self.keyringPath:
                        new_stats = fileStats(self.keyringPath)
                        if new_stats != self.keyringStats:
-                               raise portage.exception.SecurityViolation, "GPG keyring changed!"
+                               raise SecurityViolation("GPG keyring changed!")
 
        def verify(self, filename, sigfile=None):
                """Uses minimumTrust to determine if it is Valid/True or Invalid/False"""
                self._verifyKeyring()
 
                if not os.path.isfile(filename):
-                       raise portage.exception.FileNotFound, filename
+                       raise FileNotFound, filename
                
                if sigfile and not os.path.isfile(sigfile):
-                       raise portage.exception.FileNotFound, sigfile
+                       raise FileNotFound, sigfile
                
                if self.keydir and not os.path.isdir(self.keydir):
-                       raise portage.exception.DirectoryNotFound, filename
+                       raise DirectoryNotFound, filename
                
                if self.keyringPath:
                        if not os.path.isfile(self.keyringPath):
-                               raise portage.exception.FileNotFound, self.keyringPath
+                               raise FileNotFound, self.keyringPath
 
                if not os.path.isfile(filename):
-                       raise portage.exception.CommandNotFound, filename
+                       raise CommandNotFound(filename)
 
                command = GPG_BINARY + GPG_VERIFY_FLAGS + GPG_OPTIONS
                if self.keydir:
@@ -119,7 +127,7 @@ class FileChecker(object):
                result = (result >> 8)
        
                if signal:
-                       raise SignalCaught, "Signal: %d" % (signal)
+                       raise PortageException("Signal: %d" % (signal))
        
                trustLevel     = UNTRUSTED
                if result == 0:
@@ -127,22 +135,22 @@ class FileChecker(object):
                        #if portage.output.find("WARNING") != -1:
                        #       trustLevel = MARGINAL
                        if portage.output.find("BAD") != -1:
-                               raise portage.exception.InvalidSignature, filename
+                               raise InvalidSignature(filename)
                elif result == 1:
                        trustLevel   = EXISTS
                        if portage.output.find("BAD") != -1:
-                               raise portage.exception.InvalidSignature, filename
+                               raise InvalidSignature(filename)
                elif result == 2:
                        trustLevel   = UNTRUSTED
                        if portage.output.find("could not be verified") != -1:
-                               raise portage.exception.MissingSignature, filename
+                               raise MissingSignature(filename)
                        if portage.output.find("public key not found") != -1:
                                if self.keyringIsTrusted: # We trust the ring, but not the key specifically.
                                        trustLevel = MARGINAL
                                else:
-                                       raise portage.exception.InvalidSignature, filename+" (Unknown Signature)"
+                                       raise InvalidSignature(filename+"(Unknown Signature)")
                else:
-                       raise portage.exception.UnknownCondition, "GPG returned unknown result: %d" % (result)
+                       raise PortageException("GPG returned unknown result: %d" % (result))
        
                if trustLevel >= self.minimumTrust:
                        return True
index 2798044755eaf0f4cc3e46cde46e6b6d54f84f4e..004108eb7515cfaf9ed451dd10af71ff5dd4f701 100644 (file)
@@ -23,7 +23,7 @@ def lockfile(mypath, wantnewlockfile=0, unlinkfile=0, waiting_msg=None):
        import fcntl
 
        if not mypath:
-               raise InvalidData, "Empty path given"
+               raise InvalidData("Empty path given")
 
        if type(mypath) == types.StringType and mypath[-1] == '/':
                mypath = mypath[:-1]
@@ -44,7 +44,7 @@ def lockfile(mypath, wantnewlockfile=0, unlinkfile=0, waiting_msg=None):
        
        if type(mypath) == types.StringType:
                if not os.path.exists(os.path.dirname(mypath)):
-                       raise DirectoryNotFound, os.path.dirname(mypath)
+                       raise DirectoryNotFound(os.path.dirname(mypath))
                if not os.path.exists(lockfilename):
                        old_mask=os.umask(000)
                        myfd = os.open(lockfilename, os.O_CREAT|os.O_RDWR,0660)
@@ -65,7 +65,8 @@ def lockfile(mypath, wantnewlockfile=0, unlinkfile=0, waiting_msg=None):
                myfd = mypath
 
        else:
-               raise ValueError, "Unknown type passed in '%s': '%s'" % (type(mypath),mypath)
+               raise ValueError("Unknown type passed in '%s': '%s'" % \
+                       (type(mypath), mypath))
 
        # try for a non-blocking lock, if it's held, throw a message
        # we're waiting on lockfile and use a blocking attempt.
@@ -165,7 +166,7 @@ def unlockfile(mytuple):
        except OSError:
                if type(lockfilename) == types.StringType:
                        os.close(myfd)
-               raise IOError, "Failed to unlock file '%s'\n" % lockfilename
+               raise IOError("Failed to unlock file '%s'\n" % lockfilename)
 
        try:
                # This sleep call was added to allow other processes that are
@@ -230,7 +231,9 @@ def hardlink_lockfile(lockfilename, max_wait=14400):
                os.close(myfd)
        
                if not os.path.exists(myhardlock):
-                       raise FileNotFound, _("Created lockfile is missing: %(filename)s") % {"filename":myhardlock}
+                       raise FileNotFound(
+                               _("Created lockfile is missing: %(filename)s") % \
+                               {"filename" : myhardlock})
 
                try:
                        res = os.link(myhardlock, lockfilename)