Commits

Kang Zhang committed dd16b30

Remove trigger item from setup.py

Comments (0)

Files changed (8)

 ---------------------------
 What is Python keyring lib?
 ---------------------------
+
 The Python keyring lib provides a easy way to access the system keyring service 
 from python. It can be used in any application that needs safe password storage.
 
 -------------------------
 Installation Instructions
 -------------------------
+
 easy_install or pip
 ===================
 
 
 API interface 
 =============
+
 The keyring lib has two functions: 
 
 * ``get_password(service, username)`` : Returns the password stored in keyring. 
 
 Example
 =======
+
 Here's an example of using keyring for application authorization. It can be 
 found in the demo folder of the repository. Note that the faked auth function 
 only returns true when the password equals to the username.

build_ext.py

-"""
-build_ext.py
-
-Created by Kang Zhang on 2009-08-07
-"""
-
-import sys
-import commands
-
-from distutils.core import Extension
-from distutils.command.build_ext import build_ext
-
-def pkg_check(packages):
-    """Return false if not all packages has been installed properly.
-    """
-    status, output = commands.getstatusoutput("pkg-config --exists %s" % 
-                                                    ' '.join(packages))
-    return len(output) == 0 and status == 0 
-
-def pkg_config(packages):
-    """Return the config parameters for all packages
-    """
-    keywords = {}
-    flag_map = {'-I':'include_dirs', '-L':'library_dirs', '-l':'libraries'}
-
-    for token in commands.getoutput("pkg-config --libs --cflags %s" % 
-                                                ' '.join(packages)).split():
-        try:
-            key = flag_map[token[:2]]
-            keywords.setdefault(key, []).append(token[2:])
-        except KeyError:
-            keywords.setdefault('extra_link_args', []).append(token)
-
-    return keywords
-
-def kde_config(keywords):
-    """Add the compile parameter for kdelibs
-    """
-
-    # KDE guys hate pkg-config, so we need due with it seperately. :-(
-    # See following link for more details
-    #       http://lists.kde.org/?t=109647896600005&r=1&w=2
-
-    keywords.setdefault('libraries', []).append('kdeui')
-    libs = commands.getoutput("kde4-config --path lib").split(':')
-    if len(libs) == 0:
-        libs = commands.getoutput("kde-config --path lib").split(':')
-    keywords.setdefault('library_dirs', []).extend(libs)
-    return keywords
-
-class KeyringBuildExt(build_ext):
-    """Helper class to detect the enviroment and install the keyrings.
-    """
-    
-    def __init__(self, dist):
-        build_ext.__init__(self, dist)
-
-    def build_extensions(self):
-        """Collect the extensions that can be installed.
-        """
-        exts = []
-        self.extensions = exts
-        platform = sys.platform
-        
-        if platform in ['darwin', 'mac']:
-            # Mac OS X, keychain enabled
-            osx_keychain_module = Extension('osx_keychain',
-                            library_dirs = ['/System/Library/Frameworks/'],
-                            sources = ['keyring/backends/osx_keychain.c'],
-                            extra_link_args = ['-framework', 'Security',
-                                '-framework', 'CoreFoundation', '-framework',
-                                'CoreServices'])
-            exts.append(osx_keychain_module)
-
-        gnome_keyring_libs = ['dbus-1', 'glib-2.0', 'gnome-keyring-1']
-        if pkg_check(gnome_keyring_libs):
-            # gnome-keyring installed
-            gnome_keychain_module = Extension('gnome_keyring',
-                            sources = ['keyring/backends/gnome_keyring.c'],
-                            **pkg_config(gnome_keyring_libs)
-                )
-            exts.append(gnome_keychain_module)
-
-        kde_kwallet_libs = ['dbus-1', 'glib-2.0', 'QtGui']
-        if pkg_check(kde_kwallet_libs):
-            # KDE Kwallet is installed.
-            kde_kwallet_module = Extension('kde_kwallet',
-                            sources = ['keyring/backends/kde_kwallet.cpp'],
-                            **kde_config(pkg_config(kde_kwallet_libs))
-                )
-            exts.append(kde_kwallet_module)
-
-        if platform in ['win32'] and sys.getwindowsversion()[-2] == 2:
-            # windows 2k+
-            win32_crypto_module = Extension('win32_crypto',
-                    libraries = ['crypt32'],
-                    sources = ['keyring/backends/win32_crypto.c'],)
-            exts.append(win32_crypto_module)
-
-        build_ext.build_extensions(self)
+"""
+build_ext.py
+
+Created by Kang Zhang on 2009-08-07
+"""
+
+import sys
+import commands
+
+from distutils.core import Extension
+
+def pkg_check(packages):
+    """Return false if not all packages has been installed properly.
+    """
+    status, output = commands.getstatusoutput("pkg-config --exists %s" % 
+                                                    ' '.join(packages))
+    return len(output) == 0 and status == 0 
+
+def pkg_config(packages):
+    """Return the config parameters for all packages
+    """
+    keywords = {}
+    flag_map = {'-I':'include_dirs', '-L':'library_dirs', '-l':'libraries'}
+
+    for token in commands.getoutput("pkg-config --libs --cflags %s" % 
+                                                ' '.join(packages)).split():
+        try:
+            key = flag_map[token[:2]]
+            keywords.setdefault(key, []).append(token[2:])
+        except KeyError:
+            keywords.setdefault('extra_link_args', []).append(token)
+
+    return keywords
+
+def kde_config(keywords):
+    """Add the compile parameter for kdelibs
+    """
+
+    # KDE guys hate pkg-config, so we need due with it seperately. :-(
+    # See following link for more details
+    #       http://lists.kde.org/?t=109647896600005&r=1&w=2
+
+    keywords.setdefault('libraries', []).append('kdeui')
+    libs = commands.getoutput("kde4-config --path lib").split(':')
+    if len(libs) == 0:
+        libs = commands.getoutput("kde-config --path lib").split(':')
+    keywords.setdefault('library_dirs', []).extend(libs)
+    return keywords
+
+def get_extensions():
+    """Collect the extensions that can be installed.
+    """
+    exts = []
+    platform = sys.platform
+    
+    if platform in ['darwin', 'mac']:
+        # Mac OS X, keychain enabled
+        osx_keychain_module = Extension('osx_keychain',
+                        library_dirs = ['/System/Library/Frameworks/'],
+                        sources = ['keyring/backends/osx_keychain.c'],
+                        extra_link_args = ['-framework', 'Security',
+                            '-framework', 'CoreFoundation', '-framework',
+                            'CoreServices'])
+        exts.append(osx_keychain_module)
+
+    gnome_keyring_libs = ['dbus-1', 'glib-2.0', 'gnome-keyring-1']
+    if pkg_check(gnome_keyring_libs):
+        # gnome-keyring installed
+        gnome_keychain_module = Extension('gnome_keyring',
+                        sources = ['keyring/backends/gnome_keyring.c'],
+                        **pkg_config(gnome_keyring_libs)
+            )
+        exts.append(gnome_keychain_module)
+
+    kde_kwallet_libs = ['dbus-1', 'glib-2.0', 'QtGui']
+    if pkg_check(kde_kwallet_libs):
+        # KDE Kwallet is installed.
+        kde_kwallet_module = Extension('kde_kwallet',
+                        sources = ['keyring/backends/kde_kwallet.cpp'],
+                        **kde_config(pkg_config(kde_kwallet_libs))
+            )
+        exts.append(kde_kwallet_module)
+
+    if platform in ['win32'] and sys.getwindowsversion()[-2] == 2:
+        # windows 2k+
+        win32_crypto_module = Extension('win32_crypto',
+                libraries = ['crypt32'],
+                sources = ['keyring/backends/win32_crypto.c'],)
+        exts.append(win32_crypto_module)
+
+    return exts

keyring/__init__.py

 
 Created by Kang Zhang on 2009-07-09
 """
-from core import set_keyring, get_keyring, set_password, get_password 
+import logging
+logger = logging.getLogger('keyring')
+
+from core import set_keyring, get_keyring, set_password, get_password

keyring/backend.py

 _BLOCK_SIZE = 32
 _PADDING = '0'
 
-class KeyringBackend():
+class KeyringBackend(object):
     """The abstract base class of the keyring, every backend must implement
     this interface.
     """
         return -1
 
     @abstractmethod
-    def get_password(self, service, username): 
+    def get_password(self, service, username):
         """Get password of the username for the service
         """
         pass
 
     @abstractmethod
-    def set_password(self, service, username, password): 
+    def set_password(self, service, username, password):
         """Set password for the username of the service
         """
         return -1
 
 class _ExtensionKeyring(KeyringBackend):
-    """_ExtensionKeyring is a adaptor class for the platform related keyring 
+    """_ExtensionKeyring is a adaptor class for the platform related keyring
     backends.
     """
     def __init__(self):
         """Return the keyring implementation handler
         """
         return None
-    
+
     def _recommend(self):
         """If this keyring is recommanded on current enviroment.
         """
             return -1
         elif self._recommend():
             return 1
-        return 0 
+        return 0
 
     def get_password(self, service, username):
         """Override the get_password() in KeyringBackend.
         """Overide the set_password() in KeyringBackend.
         """
         return self.keyring_impl.password_set(service, username, password)
- 
+
 class OSXKeychain(_ExtensionKeyring):
     """The keyring backend based on Keychain Service of the Mac OSX
     """
     def _recommend(self):
         """Recommend for all OSX enviroment.
         """
-        return sys.platform == 'darwin' 
+        return sys.platform == 'darwin'
 
 class GnomeKeyring(_ExtensionKeyring):
     """The keyring backend using Gnome Keyring.
     def _recommend(self):
         """Recommend this keyring when Gnome is running.
         """
-        # Gnome is running 
+        # Gnome is running
         return os.getenv("GNOME_DESKTOP_SESSION_ID") is not None
 
-      
+
 class KDEKWallet(_ExtensionKeyring):
     """The keyring backend based on KDE KWallet
     """
         """
         import kde_kwallet
         return kde_kwallet
- 
+
     def _recommend(self):
         """Recommend this keyring backend when KDE is running.
         """
-        # KDE is running 
+        # KDE is running
         return os.getenv("KDE_FULL_SESSION") == "true"
 
 class BasicFileKeyring(KeyringBackend):
-    """BasicFileKeyring is a filebased implementation of keyring. It store the 
-    password directly in the file, and supports the encryption and decryption.
-    The encrypted password is stroed in base64 format.
+    """BasicFileKeyring is a filebased implementation of keyring.
+
+    It stores the password directly in the file, and supports the
+    encryption and decryption. The encrypted password is stroed in base64
+    format.
     """
 
     def __init__(self):
         self.file_path = os.path.join(os.path.expanduser("~"), self.filename())
-    
+
     @abstractmethod
     def filename(self):
         """Return the filename used to store the passwords.
         """
         # load the passwords from the file
         config = ConfigParser.RawConfigParser()
-        if os.path.exists(self.file_path): 
+        if os.path.exists(self.file_path):
             config.read(self.file_path)
 
         # fetch the password
             password_encrypted = password_base64.decode("base64")
             # decrypted the password
             password = self.decrypt(password_encrypted)
-        except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): 
+        except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
             password = None
         return password
 
     def set_password(self, service, username, password):
         """Write the password in the file.
         """
-        # encrypt the password 
+        # encrypt the password
         password_encrypted = self.encrypt(password)
         # load the password from the disk
         config = ConfigParser.RawConfigParser()
-        if os.path.exists(self.file_path): 
+        if os.path.exists(self.file_path):
             config.read(self.file_path)
 
         # encode with base64
     def __init__(self):
         super(CryptedFileKeyring, self).__init__()
         self.crypted_password = None
-        
+
     def filename(self):
         """Return the filename for the password file.
         """
         """Init the password file, set the password for it.
         """
 
-        print "Please set a password for your new keyring"
+        print("Please set a password for your new keyring")
         password = None
         while 1:
             if not password:
                 password = None
                 continue
             break
-        
+
         # hash the password
         self.crypted_password = crypt.crypt(password, password)
 
         config = ConfigParser.RawConfigParser()
         config.add_section(_KEYRING_SETTING)
         config.set(_KEYRING_SETTING, _CRYPTED_PASSWORD, self.crypted_password)
-        
+
         config_file = open(self.file_path,'w')
         config.write(config_file)
 
         if not self._auth(password):
             sys.stderr.write("Wrong password for the keyring.\n")
             raise ValueError("Wrong password")
-        
+
         # init the cipher with the password
         from Crypto.Cipher import AES
         # pad to _BLOCK_SIZE bytes
         password = password + (_BLOCK_SIZE - len(password) % _BLOCK_SIZE) * \
                                                                     _PADDING
         return AES.new(password, AES.MODE_CFB)
-        
+
     def encrypt(self, password):
         """Encrypt the given password using the pycryto.
         """
         try:
             import win32_crypto
             self.crypt_handler = win32_crypto
-        except ImportError: 
+        except ImportError:
             self.crypt_handler = None
 
     def filename(self):
         if self.crypt_handler is not None and sys.platform == 'win32':
             major, minor, build, platform, text = sys.getwindowsversion()
             if platform == 2:
-                # recommend for windows 2k+ 
+                # recommend for windows 2k+
                 return 1
         return -1
 
     """
     global _all_keyring
     if _all_keyring is None:
-        _all_keyring = [ OSXKeychain(), GnomeKeyring(), KDEKWallet(), 
-                            CryptedFileKeyring(), UncryptedFileKeyring(), 
+        _all_keyring = [ OSXKeychain(), GnomeKeyring(), KDEKWallet(),
+                            CryptedFileKeyring(), UncryptedFileKeyring(),
                             Win32CryptoKeyring()]
     return _all_keyring
 
 """
 import os
 import ConfigParser
-import imp 
+import imp
 import sys
 import backend
 
 def set_keyring(keyring):
-    """Set current keyring backend. 
+    """Set current keyring backend.
     """
     global _keyring_backend
     if isinstance(keyring, backend.KeyringBackend):
     return _keyring_backend.set_password(service_name, username, password)
 
 def init_backend():
-    """first try to load the keyring in the config file, if it has not 
+    """first try to load the keyring in the config file, if it has not
     been decleared, assign a defult keyring according to the platform.
     """
     #select a backend according to the config file
     set_keyring(keyring_impl)
 
 def load_config():
-    """load a keyring using the config file, the config file can be 
+    """load a keyring using the config file, the config file can be
     in the current working directory, or in the user's home directory.
     """
     keyring_impl = None
     if os.path.exists(keyring_cfg):
         config = ConfigParser.RawConfigParser()
         config.read(keyring_cfg)
-        # load the keyring-path option 
-        try: 
+        # load the keyring-path option
+        try:
             keyring_path = config.get("backend", "keyring-path").strip()
-        except ConfigParser.NoOptionError: 
+        except ConfigParser.NoOptionError:
             keyring_path = None
         # load the keyring class name, and load it
         try:
                 module_file, pathname, description = module_info
                 module = imp.load_module(path_list[0], module_file, \
                                                           pathname, description)
-                if module_file: 
+                if module_file:
                     module_file.close()
-                #print module.__path__
+
                 if len(path_list) > 1:
                     # for the class name containing dots
                     sub_name = '.'.join(path_list[1:])
                     sub_path = path
 
-                    try: 
+                    try:
                         sub_path = path + module.__path__
-                    except AttributeError: 
+                    except AttributeError:
                         return module
-                    
+
                     return load_module(sub_name, sub_path)
                 return module
-            
+
             try:
                 # avoid import the imported modules
                 module = sys.modules[keyring_name[:keyring_name.rfind('.')]]
-            except KeyError: 
+            except KeyError:
                 module = load_module( keyring_name, sys.path+[keyring_path])
 
             keyring_class = keyring_name.split('.')[-1].strip()
             exec  "keyring_temp = module." + keyring_class + "() " in locals()
-            
+
             keyring_impl = keyring_temp
         except (ConfigParser.NoOptionError, ImportError):
-            print "Keyring Config file does not write correctly.\n" + \
-                  "Config file: %s" % keyring_cfg
-    
+            logger.warning("Keyring Config file does not write correctly.\n" + \
+                           "Config file: %s" % keyring_cfg)
+
     return keyring_impl
 
 # init the _keyring_backend

keyring/tests/test_backend.py

             from Crypto.Cipher import AES
             return 0
         except ImportError:
-            return -1
+            pass
+        return -1
 
 class Win32CryptoKeyringTestCase(FileKeyringTestCase):
     def init_keyring(self):
 """
 setup.py
 
+Setup the Keyring Lib for Python.
 """
 
 from distutils.core import setup, Extension
-from build_ext import KeyringBuildExt
+from extensions import get_extensions
 
-"""Setup the Keyring Lib for Python.
-"""
 setup(name = 'keyring',
       version = "0.1",
       description = "Store and access your passwords safely.",
       long_description = open('README.txt').read(),
       platforms = ["Many"],
       packages = ['keyring'],
-      # Buildinfo
-      cmdclass = { 'build_ext':KeyringBuildExt },
-      # Dummy item, to trigger the build_ext
-      ext_modules = [Extension('osx_keychain',
-                                ['keyring/backends/osx_keychain.c'])]
+      ext_modules = get_extensions()
     )