Example #1
0
class Config:

    OUT_MKT_EDDN = 1
    # OUT_MKT_BPC     = 2	# No longer supported
    OUT_MKT_TD = 4
    OUT_MKT_CSV = 8
    OUT_SHIP = 16
    OUT_SHIP_EDS = 16  # Replaced by OUT_SHIP
    # OUT_SYS_FILE    = 32	# No longer supported
    # OUT_STAT        = 64	# No longer available
    OUT_SHIP_CORIOLIS = 128  # Replaced by OUT_SHIP
    OUT_STATION_ANY = OUT_MKT_EDDN | OUT_MKT_TD | OUT_MKT_CSV | OUT_SHIP | OUT_SHIP_EDS | OUT_SHIP_CORIOLIS
    # OUT_SYS_EDSM      = 256	# Now a plugin
    # OUT_SYS_AUTO    = 512	# Now always automatic
    OUT_MKT_MANUAL = 1024
    OUT_SYS_EDDN = 2048
    OUT_SYS_DELAY = 4096

    # shipyard setting
    SHIPYARD_EDSHIPYARD = 0
    SHIPYARD_CORIOLIS = 1

    if platform == 'darwin':

        def __init__(self):
            self.app_dir = join(
                NSSearchPathForDirectoriesInDomains(
                    NSApplicationSupportDirectory, NSUserDomainMask, True)[0],
                appname)
            if not isdir(self.app_dir):
                mkdir(self.app_dir)

            self.plugin_dir = join(self.app_dir, 'plugins')
            if not isdir(self.plugin_dir):
                mkdir(self.plugin_dir)

            self.internal_plugin_dir = getattr(
                sys, 'frozen', False) and normpath(
                    join(
                        dirname(
                            sys.executable.decode(
                                sys.getfilesystemencoding())),
                        pardir, 'Library', 'plugins')) or join(
                            dirname(__file__), 'plugins')

            self.default_journal_dir = join(
                NSSearchPathForDirectoriesInDomains(
                    NSApplicationSupportDirectory, NSUserDomainMask, True)[0],
                'Frontier Developments', 'Elite Dangerous')

            self.home = expanduser('~')

            self.respath = getattr(sys, 'frozen', False) and normpath(
                join(
                    dirname(sys.executable.decode(
                        sys.getfilesystemencoding())), pardir,
                    'Resources')) or dirname(__file__)

            if not getattr(sys, 'frozen', False):
                # Don't use Python's settings if interactive
                self.identifier = 'uk.org.marginal.%s' % appname.lower()
                NSBundle.mainBundle().infoDictionary(
                )['CFBundleIdentifier'] = self.identifier
            else:
                self.identifier = NSBundle.mainBundle().bundleIdentifier()
            self.defaults = NSUserDefaults.standardUserDefaults()
            self.settings = dict(
                self.defaults.persistentDomainForName_(self.identifier)
                or {})  # make writeable

            # Check out_dir exists
            if not self.get('outdir') or not isdir(self.get('outdir')):
                self.set(
                    'outdir',
                    NSSearchPathForDirectoriesInDomains(
                        NSDocumentDirectory, NSUserDomainMask, True)[0])

        def get(self, key):
            val = self.settings.get(key)
            if val is None:
                return None
            elif hasattr(val, '__iter__'):
                return list(val)  # make writeable
            else:
                return unicode(val)

        def getint(self, key):
            try:
                return int(self.settings.get(
                    key, 0))  # should already be int, but check by casting
            except:
                return 0

        def set(self, key, val):
            self.settings[key] = val

        def delete(self, key):
            self.settings.pop(key, None)

        def save(self):
            self.defaults.setPersistentDomain_forName_(self.settings,
                                                       self.identifier)
            self.defaults.synchronize()

        def close(self):
            self.save()
            self.defaults = None

    elif platform == 'win32':

        def __init__(self):

            self.app_dir = join(KnownFolderPath(FOLDERID_LocalAppData),
                                appname)
            if not isdir(self.app_dir):
                mkdir(self.app_dir)

            self.plugin_dir = join(self.app_dir, 'plugins')
            if not isdir(self.plugin_dir):
                mkdir(self.plugin_dir)

            self.internal_plugin_dir = join(
                dirname(
                    getattr(sys, 'frozen', False)
                    and sys.executable.decode(sys.getfilesystemencoding())
                    or __file__), u'plugins')

            # expanduser in Python 2 on Windows doesn't handle non-ASCII - http://bugs.python.org/issue13207
            self.home = KnownFolderPath(FOLDERID_Profile) or u'\\'

            journaldir = KnownFolderPath(FOLDERID_SavedGames)
            self.default_journal_dir = journaldir and join(
                journaldir, 'Frontier Developments', 'Elite Dangerous') or None

            self.respath = dirname(
                getattr(sys, 'frozen', False)
                and sys.executable.decode(sys.getfilesystemencoding())
                or __file__)

            self.identifier = applongname

            self.hkey = HKEY()
            disposition = DWORD()
            if RegCreateKeyEx(HKEY_CURRENT_USER,
                              r'Software\Marginal\EDMarketConnector', 0, None,
                              0, KEY_ALL_ACCESS, None, ctypes.byref(self.hkey),
                              ctypes.byref(disposition)):
                raise Exception()

            if disposition.value == REG_CREATED_NEW_KEY:

                # Migrate pre-1.3.4 registry location
                oldkey = HKEY()
                if not RegOpenKeyEx(HKEY_CURRENT_USER,
                                    r'Software\EDMarketConnector', 0,
                                    KEY_ALL_ACCESS, ctypes.byref(oldkey)):
                    RegCopyTree(oldkey, None, self.hkey)
                    RegCloseKey(oldkey)
                    RegDeleteKey(HKEY_CURRENT_USER,
                                 r'Software\EDMarketConnector')

                # set WinSparkle defaults - https://github.com/vslavik/winsparkle/wiki/Registry-Settings
                sparklekey = HKEY()
                if not RegCreateKeyEx(self.hkey, 'WinSparkle', 0, None, 0,
                                      KEY_ALL_ACCESS, None,
                                      ctypes.byref(sparklekey),
                                      ctypes.byref(disposition)):
                    if disposition.value == REG_CREATED_NEW_KEY:
                        buf = ctypes.create_unicode_buffer('1')
                        RegSetValueEx(sparklekey, 'CheckForUpdates', 0, 1, buf,
                                      len(buf) * 2)
                        buf = ctypes.create_unicode_buffer(
                            unicode(update_interval))
                        RegSetValueEx(sparklekey, 'UpdateInterval', 0, 1, buf,
                                      len(buf) * 2)
                    RegCloseKey(sparklekey)

            if not self.get('outdir') or not isdir(self.get('outdir')):
                self.set('outdir',
                         KnownFolderPath(FOLDERID_Documents) or self.home)

        def get(self, key):
            typ = DWORD()
            size = DWORD()
            if RegQueryValueEx(self.hkey, key, 0, ctypes.byref(typ), None,
                               ctypes.byref(size)) or typ.value not in [
                                   REG_SZ, REG_MULTI_SZ
                               ]:
                return None
            buf = ctypes.create_unicode_buffer(size.value / 2)
            if RegQueryValueEx(self.hkey, key, 0, ctypes.byref(typ), buf,
                               ctypes.byref(size)):
                return None
            elif typ.value == REG_MULTI_SZ:
                return [
                    x for x in ctypes.wstring_at(buf,
                                                 len(buf) - 2).split(u'\x00')
                ]
            else:
                return unicode(buf.value)

        def getint(self, key):
            typ = DWORD()
            size = DWORD(4)
            val = DWORD()
            if RegQueryValueEx(self.hkey, key, 0, ctypes.byref(typ),
                               ctypes.byref(val),
                               ctypes.byref(size)) or typ.value != REG_DWORD:
                return 0
            else:
                return val.value

        def set(self, key, val):
            if isinstance(val, basestring):
                buf = ctypes.create_unicode_buffer(val)
                RegSetValueEx(self.hkey, key, 0, REG_SZ, buf, len(buf) * 2)
            elif isinstance(val, numbers.Integral):
                RegSetValueEx(self.hkey, key, 0, REG_DWORD,
                              ctypes.byref(DWORD(val)), 4)
            elif hasattr(val, '__iter__'):  # iterable
                stringval = u'\x00'.join(
                    [unicode(x) or u' ' for x in val] +
                    [u''])  # null terminated non-empty strings
                buf = ctypes.create_unicode_buffer(stringval)
                RegSetValueEx(self.hkey, key, 0, REG_MULTI_SZ, buf,
                              len(buf) * 2)
            else:
                raise NotImplementedError()

        def delete(self, key):
            RegDeleteValue(self.hkey, key)

        def save(self):
            pass  # Redundant since registry keys are written immediately

        def close(self):
            RegCloseKey(self.hkey)
            self.hkey = None

    elif platform == 'linux2':

        SECTION = 'config'

        def __init__(self):

            # http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
            self.app_dir = join(
                getenv('XDG_DATA_HOME', expanduser('~/.local/share')), appname)
            if not isdir(self.app_dir):
                makedirs(self.app_dir)

            self.plugin_dir = join(self.app_dir, 'plugins')
            if not isdir(self.plugin_dir):
                mkdir(self.plugin_dir)

            self.internal_plugin_dir = join(dirname(__file__), 'plugins')

            self.default_journal_dir = None

            self.home = expanduser('~')

            self.respath = dirname(__file__)

            self.identifier = 'uk.org.marginal.%s' % appname.lower()

            self.filename = join(
                getenv('XDG_CONFIG_HOME', expanduser('~/.config')), appname,
                '%s.ini' % appname)
            if not isdir(dirname(self.filename)):
                makedirs(dirname(self.filename))

            self.config = RawConfigParser()
            try:
                self.config.readfp(codecs.open(self.filename, 'r', 'utf-8'))
            except:
                self.config.add_section(self.SECTION)

            if not self.get('outdir') or not isdir(self.get('outdir')):
                self.set('outdir', expanduser('~'))

        def get(self, key):
            try:
                val = self.config.get(self.SECTION, key)
                if u'\n' in val:
                    return [self._unescape(x) for x in val.split(u'\n')[:-1]]
                else:
                    return self._unescape(val)
            except:
                return None

        def getint(self, key):
            try:
                return self.config.getint(self.SECTION, key)
            except:
                return 0

        def set(self, key, val):
            if isinstance(val, basestring) or isinstance(
                    val, numbers.Integral):
                self.config.set(self.SECTION, key, self._escape(val))
            elif hasattr(val, '__iter__'):  # iterable
                self.config.set(
                    self.SECTION, key,
                    u'\n'.join([self._escape(x) for x in val] + [u';']))
            else:
                raise NotImplementedError()

        def delete(self, key):
            self.config.remove_option(self.SECTION, key)

        def save(self):
            with codecs.open(self.filename, 'w', 'utf-8') as h:
                h.write(unicode(self.config.data))

        def close(self):
            self.save()
            self.config = None

        def _escape(self, val):
            return unicode(val).replace(u'\\', u'\\\\').replace(
                u'\n', u'\\n').replace(u';', u'\\;')

        def _unescape(self, val):
            chars = list(val)
            i = 0
            while i < len(chars):
                if chars[i] == '\\':
                    chars.pop(i)
                    if chars[i] == 'n':
                        chars[i] = '\n'
                i += 1
            return u''.join(chars)

    else:  # ???

        def __init__(self):
            raise NotImplementedError('Implement me')

    # Common

    def get_password(self, account):
        return keyring.get_password(self.identifier, account)

    def set_password(self, account, password):
        keyring.set_password(self.identifier, account, password)

    def delete_password(self, account):
        try:
            keyring.delete_password(self.identifier, account)
        except:
            pass  # don't care - silently fail
Example #2
0
    def enable_yum_plugins(cls):
        """
        This function tries to enable yum plugins: subscription-manager and product-id.
        It takes no action, when automatic enabling of yum plugins is disabled in rhsm.conf.
        :return: It returns list of enabled plugins
        """

        # When user doesn't want to automatically enable yum plugins, then return empty list
        if cls.is_auto_enable_enabled() is False:
            log.info(
                'The rhsm.auto_enable_yum_plugins is disabled. Skipping the enablement of yum plugins.'
            )
            return []

        log.debug('The rhsm.auto_enable_yum_plugins is enabled')

        # List of successfully enabled plugins
        enabled_yum_plugins = []
        plugin_dir = ""
        if version.use_dnf:
            plugin_dir = cls.DNF_PLUGIN_DIR
        else:
            plugin_dir = cls.YUM_PLUGIN_DIR

        # Go through the list of yum plugins and try to find configuration
        # file of these plugins.
        for yum_plugin_name in cls.YUM_PLUGINS:
            yum_plugin_file_name = plugin_dir + '/' + yum_plugin_name + '.conf'
            yum_plugin_config = ConfigParser()
            try:
                result = yum_plugin_config.read(yum_plugin_file_name)
            except Exception as err:
                # Capture all errors during reading yum plugin conf file
                # report them and skip this conf file
                log.error(
                    "Error during reading yum plugin config file '%s': %s. Skipping this file."
                    % (yum_plugin_file_name, err))
                continue

            if len(result) == 0:
                log.info(
                    'Configuration file of yum plugin: "%s" cannot be read' %
                    yum_plugin_file_name)
                continue

            is_plugin_enabled = False
            if not yum_plugin_config.has_section('main'):
                log.warn(
                    'Configuration file of yum plugin: "%s" does not include main section. Adding main section.'
                    % yum_plugin_file_name)
                yum_plugin_config.add_section('main')
            elif yum_plugin_config.has_option('main', 'enabled'):
                try:
                    # Options 'enabled' can be 0 or 1
                    is_plugin_enabled = yum_plugin_config.getint(
                        'main', 'enabled')
                except ValueError:
                    try:
                        # Options 'enabled' can be also: true or false
                        is_plugin_enabled = yum_plugin_config.getboolean(
                            'main', 'enabled')
                    except ValueError:
                        log.warn(
                            "File %s has wrong value of options: 'enabled' in section: 'main' (not a int nor boolean)"
                            % yum_plugin_file_name)

            if is_plugin_enabled == cls.YUM_PLUGIN_ENABLED:
                log.debug('Yum plugin: "%s" already enabled. Nothing to do.' %
                          yum_plugin_file_name)
            else:
                log.warn('Enabling yum plugin: "%s".' % yum_plugin_file_name)
                # Change content of plugin configuration file and enable this plugin.
                with open(yum_plugin_file_name, 'w') as cfg_file:
                    yum_plugin_config.set('main', 'enabled',
                                          cls.YUM_PLUGIN_ENABLED)
                    yum_plugin_config.write(cfg_file)
                enabled_yum_plugins.append(yum_plugin_file_name)

        return enabled_yum_plugins
Example #3
0
    def _enable_plugins(cls, pkg_mgr_name, plugin_dir):
        """
        This class method tries to enable plugins for DNF or YUM
        :param pkg_mgr_name: It can be "dnf" or "yum"
        :type pkg_mgr_name: str
        :param plugin_dir: Directory with configuration files for (dnf/yum) plugins
        :type plugin_dir: str
        :return:
        """
        # List of successfully enabled plugins
        enabled_lugins = []
        # Go through the list of yum plugins and try to find configuration
        # file of these plugins.
        for plugin_name in cls.PLUGINS:
            plugin_file_name = plugin_dir + '/' + plugin_name + '.conf'
            plugin_config = ConfigParser()
            try:
                result = plugin_config.read(plugin_file_name)
            except Exception as err:
                # Capture all errors during reading yum plugin conf file
                # report them and skip this conf file
                log.error(
                    "Error during reading %s plugin config file '%s': %s. Skipping this file."
                    % (pkg_mgr_name, plugin_file_name, err))
                continue

            if len(result) == 0:
                log.info(
                    'Configuration file of %s plugin: "%s" cannot be read' %
                    (pkg_mgr_name, plugin_file_name))
                continue

            is_plugin_enabled = False
            if not plugin_config.has_section('main'):
                log.warning(
                    'Configuration file of %s plugin: "%s" does not include main section. Adding main section.'
                    % (pkg_mgr_name, plugin_file_name))
                plugin_config.add_section('main')
            elif plugin_config.has_option('main', 'enabled'):
                try:
                    # Options 'enabled' can be 0 or 1
                    is_plugin_enabled = plugin_config.getint('main', 'enabled')
                except ValueError:
                    try:
                        # Options 'enabled' can be also: true or false
                        is_plugin_enabled = plugin_config.getboolean(
                            'main', 'enabled')
                    except ValueError:
                        log.warning(
                            "File %s has wrong value of options: 'enabled' in section: 'main' (not a int nor boolean)"
                            % plugin_file_name)

            if is_plugin_enabled == cls.PLUGIN_ENABLED:
                log.debug('%s plugin: "%s" already enabled. Nothing to do.' %
                          (pkg_mgr_name, plugin_file_name))
            else:
                log.warning('Enabling %s plugin: "%s".' %
                            (pkg_mgr_name, plugin_file_name))
                # Change content of plugin configuration file and enable this plugin.
                with open(plugin_file_name, 'w') as cfg_file:
                    plugin_config.set('main', 'enabled', cls.PLUGIN_ENABLED)
                    plugin_config.write(cfg_file)
                enabled_lugins.append(plugin_file_name)

        return enabled_lugins
Example #4
0
class Config:

    OUT_MKT_EDDN      = 1
    OUT_MKT_BPC       = 2
    OUT_MKT_TD        = 4
    OUT_MKT_CSV       = 8
    OUT_SHIP_EDS      = 16
    # OUT_SYS_FILE    = 32	# No longer supported
    # OUT_STAT        = 64	# No longer available
    OUT_SHIP_CORIOLIS = 128
    OUT_STATION_ANY   = OUT_MKT_EDDN|OUT_MKT_BPC|OUT_MKT_TD|OUT_MKT_CSV|OUT_SHIP_EDS|OUT_SHIP_CORIOLIS
    OUT_SYS_EDSM      = 256
    # OUT_SYS_AUTO    = 512	# Now always automatic
    OUT_MKT_MANUAL    = 1024
    OUT_SYS_EDDN      = 2048
    OUT_SYS_DELAY     = 4096

    if platform=='darwin':

        def __init__(self):
            self.app_dir = join(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], appname)
            if not isdir(self.app_dir):
                mkdir(self.app_dir)

            self.plugin_dir = join(self.app_dir, 'plugins')
            if not isdir(self.plugin_dir):
                mkdir(self.plugin_dir)

            self.default_journal_dir = join(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], 'Frontier Developments', 'Elite Dangerous')

            self.home = expanduser('~')

            self.respath = getattr(sys, 'frozen', False) and normpath(join(dirname(sys.executable), pardir, 'Resources')) or dirname(__file__)

            if not getattr(sys, 'frozen', False):
                # Don't use Python's settings if interactive
                self.bundle = 'uk.org.marginal.%s' % appname.lower()
                NSBundle.mainBundle().infoDictionary()['CFBundleIdentifier'] = self.bundle
            else:
                self.bundle = NSBundle.mainBundle().bundleIdentifier()
            self.defaults = NSUserDefaults.standardUserDefaults()
            self.settings = dict(self.defaults.persistentDomainForName_(self.bundle) or {})	# make writeable

            # Check out_dir exists
            if not self.get('outdir') or not isdir(self.get('outdir')):
                self.set('outdir', NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, True)[0])

        def get(self, key):
            val = self.settings.get(key)
            if hasattr(val, '__iter__'):
                return list(val)	# make writeable
            else:
                return val

        def getint(self, key):
            try:
                return int(self.settings.get(key, 0))	# should already be int, but check by casting
            except:
                return 0

        def set(self, key, val):
            self.settings[key] = val

        def delete(self, key):
            self.settings.pop(key, None)

        def save(self):
            self.defaults.setPersistentDomain_forName_(self.settings, self.bundle)
            self.defaults.synchronize()

        def close(self):
            self.save()
            self.defaults = None

    elif platform=='win32':

        def __init__(self):

            self.app_dir = join(KnownFolderPath(FOLDERID_LocalAppData), appname)
            if not isdir(self.app_dir):
                mkdir(self.app_dir)

            self.plugin_dir = join(self.app_dir, 'plugins')
            if not isdir(self.plugin_dir):
                mkdir(self.plugin_dir)

            # expanduser in Python 2 on Windows doesn't handle non-ASCII - http://bugs.python.org/issue13207
            self.home = KnownFolderPath(FOLDERID_Profile) or u'\\'

            journaldir = KnownFolderPath(FOLDERID_SavedGames)
            self.default_journal_dir = journaldir and join(journaldir, 'Frontier Developments', 'Elite Dangerous') or None

            self.respath = dirname(getattr(sys, 'frozen', False) and sys.executable or __file__)

            self.hkey = HKEY()
            disposition = DWORD()
            if RegCreateKeyEx(HKEY_CURRENT_USER, r'Software\Marginal\EDMarketConnector', 0, None, 0, KEY_ALL_ACCESS, None, ctypes.byref(self.hkey), ctypes.byref(disposition)):
                raise Exception()

            if disposition.value == REG_CREATED_NEW_KEY:

                # Migrate pre-1.3.4 registry location
                oldkey = HKEY()
                if not RegOpenKeyEx(HKEY_CURRENT_USER, r'Software\EDMarketConnector', 0, KEY_ALL_ACCESS, ctypes.byref(oldkey)):
                    RegCopyTree(oldkey, None, self.hkey)
                    RegCloseKey(oldkey)
                    RegDeleteKey(HKEY_CURRENT_USER, r'Software\EDMarketConnector')

                # set WinSparkle defaults - https://github.com/vslavik/winsparkle/wiki/Registry-Settings
                sparklekey = HKEY()
                if not RegCreateKeyEx(self.hkey, 'WinSparkle', 0, None, 0, KEY_ALL_ACCESS, None, ctypes.byref(sparklekey), ctypes.byref(disposition)):
                    if disposition.value == REG_CREATED_NEW_KEY:
                        buf = ctypes.create_unicode_buffer('1')
                        RegSetValueEx(sparklekey, 'CheckForUpdates', 0, 1, buf, len(buf)*2)
                        buf = ctypes.create_unicode_buffer(unicode(update_interval))
                        RegSetValueEx(sparklekey, 'UpdateInterval', 0, 1, buf, len(buf)*2)
                    RegCloseKey(sparklekey)

            if not self.get('outdir') or not isdir(self.get('outdir')):
                self.set('outdir', KnownFolderPath(FOLDERID_Documents))

        def get(self, key):
            typ  = DWORD()
            size = DWORD()
            if RegQueryValueEx(self.hkey, key, 0, ctypes.byref(typ), None, ctypes.byref(size)) or typ.value not in [REG_SZ, REG_MULTI_SZ]:
                return None
            buf = ctypes.create_unicode_buffer(size.value / 2)
            if RegQueryValueEx(self.hkey, key, 0, ctypes.byref(typ), buf, ctypes.byref(size)):
                return None
            elif typ.value == REG_MULTI_SZ:
                return [x.strip() for x in ctypes.wstring_at(buf, len(buf)-2).split(u'\x00')]
            else:
                return buf.value

        def getint(self, key):
            typ  = DWORD()
            size = DWORD(4)
            val  = DWORD()
            if RegQueryValueEx(self.hkey, key, 0, ctypes.byref(typ), ctypes.byref(val), ctypes.byref(size)) or typ.value != REG_DWORD:
                return 0
            else:
                return val.value

        def set(self, key, val):
            if isinstance(val, basestring):
                buf = ctypes.create_unicode_buffer(val)
                RegSetValueEx(self.hkey, key, 0, REG_SZ, buf, len(buf)*2)
            elif isinstance(val, numbers.Integral):
                RegSetValueEx(self.hkey, key, 0, REG_DWORD, ctypes.byref(DWORD(val)), 4)
            elif hasattr(val, '__iter__'):	# iterable
                stringval = u'\x00'.join([unicode(x) or u' ' for x in val] + [u''])	# null terminated non-empty strings
                buf = ctypes.create_unicode_buffer(stringval)
                RegSetValueEx(self.hkey, key, 0, REG_MULTI_SZ, buf, len(buf)*2)
            else:
                raise NotImplementedError()

        def delete(self, key):
            RegDeleteValue(self.hkey, key)

        def save(self):
            pass	# Redundant since registry keys are written immediately

        def close(self):
            RegCloseKey(self.hkey)
            self.hkey = None

    elif platform=='linux2':

        SECTION = 'config'

        def __init__(self):

            # http://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
            self.app_dir = join(getenv('XDG_DATA_HOME', expanduser('~/.local/share')), appname)
            if not isdir(self.app_dir):
                makedirs(self.app_dir)

            self.plugin_dir = join(self.app_dir, 'plugins')
            if not isdir(self.plugin_dir):
                mkdir(self.plugin_dir)

            self.default_journal_dir = None

            self.home = expanduser('~')

            self.respath = dirname(__file__)

            self.filename = join(getenv('XDG_CONFIG_HOME', expanduser('~/.config')), appname, '%s.ini' % appname)
            if not isdir(dirname(self.filename)):
                makedirs(dirname(self.filename))

            self.config = RawConfigParser()
            try:
                self.config.readfp(codecs.open(self.filename, 'r', 'utf-8'))
            except:
                self.config.add_section(self.SECTION)

            if not self.get('outdir') or not isdir(self.get('outdir')):
                self.set('outdir', expanduser('~'))

        def get(self, key):
            try:
                val = self.config.get(self.SECTION, key)
                if u'\n' in val:
                    return val.split(u'\n')
                else:
                    return val
            except:
                return None

        def getint(self, key):
            try:
                return self.config.getint(self.SECTION, key)
            except:
                return 0

        def set(self, key, val):
            if isinstance(val, basestring) or isinstance(val, numbers.Integral):
                self.config.set(self.SECTION, key, val)
            elif hasattr(val, '__iter__'):	# iterable
                self.config.set(self.SECTION, key, u'\n'.join([unicode(x) for x in val]))
            else:
                raise NotImplementedError()

        def delete(self, key):
            self.config.remove_option(self.SECTION, key)

        def save(self):
            with codecs.open(self.filename, 'w', 'utf-8') as h:
                h.write(unicode(self.config.data))

        def close(self):
            self.save()
            self.config = None

    else:	# ???

        def __init__(self):
            raise NotImplementedError('Implement me')
    def _enable_plugins(cls, pkg_mgr_name, plugin_dir):
        """
        This class method tries to enable plugins for DNF or YUM
        :param pkg_mgr_name: It can be "dnf" or "yum"
        :type pkg_mgr_name: str
        :param plugin_dir: Directory with configuration files for (dnf/yum) plugins
        :type plugin_dir: str
        :return:
        """
        # List of successfully enabled plugins
        enabled_lugins = []
        # Go through the list of yum plugins and try to find configuration
        # file of these plugins.
        for plugin_name in cls.PLUGINS:
            plugin_file_name = plugin_dir + '/' + plugin_name + '.conf'
            plugin_config = ConfigParser()
            try:
                result = plugin_config.read(plugin_file_name)
            except Exception as err:
                # Capture all errors during reading yum plugin conf file
                # report them and skip this conf file
                log.error(
                    "Error during reading %s plugin config file '%s': %s. Skipping this file." %
                    (pkg_mgr_name, plugin_file_name, err)
                )
                continue

            if len(result) == 0:
                log.warn('Configuration file of %s plugin: "%s" cannot be read' %
                         (pkg_mgr_name, plugin_file_name))
                continue

            is_plugin_enabled = False
            if not plugin_config.has_section('main'):
                log.warning(
                    'Configuration file of %s plugin: "%s" does not include main section. Adding main section.' %
                    (pkg_mgr_name, plugin_file_name)
                )
                plugin_config.add_section('main')
            elif plugin_config.has_option('main', 'enabled'):
                try:
                    # Options 'enabled' can be 0 or 1
                    is_plugin_enabled = plugin_config.getint('main', 'enabled')
                except ValueError:
                    try:
                        # Options 'enabled' can be also: true or false
                        is_plugin_enabled = plugin_config.getboolean('main', 'enabled')
                    except ValueError:
                        log.warning(
                            "File %s has wrong value of options: 'enabled' in section: 'main' (not a int nor boolean)" %
                            plugin_file_name
                        )

            if is_plugin_enabled == cls.PLUGIN_ENABLED:
                log.debug('%s plugin: "%s" already enabled. Nothing to do.' %
                          (pkg_mgr_name, plugin_file_name))
            else:
                log.warning('Enabling %s plugin: "%s".' % (pkg_mgr_name, plugin_file_name))
                # Change content of plugin configuration file and enable this plugin.
                with open(plugin_file_name, 'w') as cfg_file:
                    plugin_config.set('main', 'enabled', cls.PLUGIN_ENABLED)
                    plugin_config.write(cfg_file)
                enabled_lugins.append(plugin_file_name)

        return enabled_lugins
Example #6
0
    def enable_yum_plugins(cls):
        """
        This function tries to enable yum plugins: subscription-manager and product-id.
        It takes no action, when automatic enabling of yum plugins is disabled in rhsm.conf.
        :return: It returns list of enabled plugins
        """

        # When user doesn't want to automatically enable yum plugins, then return empty list
        if cls.is_auto_enable_enabled() is False:
            log.info('The rhsm.auto_enable_yum_plugins is disabled. Skipping the enablement of yum plugins.')
            return []

        log.debug('The rhsm.auto_enable_yum_plugins is enabled')

        # List of successfully enabled plugins
        enabled_yum_plugins = []

        # Go through the list of yum plugins and try to find configuration
        # file of these plugins.
        for yum_plugin_name in cls.YUM_PLUGINS:
            yum_plugin_file_name = cls.YUM_PLUGIN_DIR + '/' + yum_plugin_name + '.conf'
            yum_plugin_config = ConfigParser()
            try:
                result = yum_plugin_config.read(yum_plugin_file_name)
            except Exception as err:
                # Capture all errors during reading yum plugin conf file
                # report them and skip this conf file
                log.error(
                    "Error during reading yum plugin config file '%s': %s. Skipping this file." %
                    (yum_plugin_file_name, err)
                )
                continue

            if len(result) == 0:
                log.info('Configuration file of yum plugin: "%s" cannot be read' % yum_plugin_file_name)
                continue

            is_plugin_enabled = False
            if not yum_plugin_config.has_section('main'):
                log.warn(
                    'Configuration file of yum plugin: "%s" does not include main section. Adding main section.' %
                    yum_plugin_file_name
                )
                yum_plugin_config.add_section('main')
            elif yum_plugin_config.has_option('main', 'enabled'):
                try:
                    # Options 'enabled' can be 0 or 1
                    is_plugin_enabled = yum_plugin_config.getint('main', 'enabled')
                except ValueError:
                    try:
                        # Options 'enabled' can be also: true or false
                        is_plugin_enabled = yum_plugin_config.getboolean('main', 'enabled')
                    except ValueError:
                        log.warn(
                            "File %s has wrong value of options: 'enabled' in section: 'main' (not a int nor boolean)" %
                            yum_plugin_file_name
                        )

            if is_plugin_enabled == cls.YUM_PLUGIN_ENABLED:
                log.debug('Yum plugin: "%s" already enabled. Nothing to do.' % yum_plugin_file_name)
            else:
                log.warn('Enabling yum plugin: "%s".' % yum_plugin_file_name)
                # Change content of plugin configuration file and enable this plugin.
                with open(yum_plugin_file_name, 'w') as cfg_file:
                    yum_plugin_config.set('main', 'enabled', cls.YUM_PLUGIN_ENABLED)
                    yum_plugin_config.write(cfg_file)
                enabled_yum_plugins.append(yum_plugin_file_name)

        return enabled_yum_plugins