Ejemplo n.º 1
0
def inifile_readstring(inifilename,section,key,default=None):
    """Read a string parameter from inifile"""
    inifile = RawConfigParser()
    inifile.read(inifilename)
    if inifile.has_section(section) and inifile.has_option(section,key):
        return inifile.get(section,key)
    else:
        return default
Ejemplo n.º 2
0
def inifile_readstring(inifilename, section, key, default=None):
    """Read a string parameter from inifile"""
    inifile = RawConfigParser()
    inifile.read(inifilename)
    if inifile.has_section(section) and inifile.has_option(section, key):
        return inifile.get(section, key)
    else:
        return default
Ejemplo n.º 3
0
def inifile_readstring(inifilename, section, key, default=None):
    """Read a string parameter from inifile

    >>> inifile_writestring('c:/tranquilit/wapt/tests/test.ini','global','version','1.1.2')
    >>> print inifile_readstring('c:/tranquilit/wapt/tests/test.ini','global','version')
    1.1.2
    >>> print inifile_readstring('c:/tranquilit/wapt/tests/test.ini','global','undefaut','defvalue')
    defvalue
    """

    inifile = RawConfigParser()
    inifile.read(inifilename)
    if inifile.has_section(section) and inifile.has_option(section, key):
        return inifile.get(section, key)
    else:
        return default
Ejemplo n.º 4
0
class Config:

    OUT_EDDN = 1
    OUT_BPC  = 2
    OUT_TD   = 4
    OUT_CSV  = 8
    OUT_SHIP_EDS = 16
    OUT_LOG_FILE  = 32
    #OUT_STAT = 64	# No longer available
    OUT_SHIP_CORIOLIS = 128
    OUT_LOG_EDSM = 256
    OUT_LOG_AUTO = 512

    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.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
            self.bundle = NSBundle.mainBundle().bundleIdentifier()
            self.defaults = NSUserDefaults.standardUserDefaults()
            settings = self.defaults.persistentDomainForName_(self.bundle) or {}
            self.settings = dict(settings)

            # 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):
            return self.settings.get(key)

        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 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):

            buf = ctypes.create_unicode_buffer(MAX_PATH)
            ctypes.windll.shell32.SHGetSpecialFolderPathW(0, buf, CSIDL_LOCAL_APPDATA, 0)
            self.app_dir = join(buf.value, 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
            ctypes.windll.shell32.SHGetSpecialFolderPathW(0, buf, CSIDL_PROFILE, 0)
            self.home = buf.value

            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')):
                buf = ctypes.create_unicode_buffer(MAX_PATH)
                ctypes.windll.shell32.SHGetSpecialFolderPathW(0, buf, CSIDL_PERSONAL, 0)
                self.set('outdir', buf.value)

        def get(self, key):
            typ  = DWORD()
            size = DWORD()
            if RegQueryValueEx(self.hkey, key, 0, ctypes.byref(typ), None, ctypes.byref(size)) or typ.value != REG_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
            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)
            else:
                raise NotImplementedError()

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

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

    elif platform=='linux2':

        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.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('config')

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

        def set(self, key, val):
            assert isinstance(val, basestring) or isinstance(val, numbers.Integral), type(val)
            self.config.set('config', key, val)

        def get(self, key):
            try:
                return self.config.get('config', key)	# all values are stored as strings
            except:
                return None

        def getint(self, key):
            try:
                return int(self.config.get('config', key))	# all values are stored as strings
            except:
                return 0

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

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

    else:	# ???

        def __init__(self):
            raise NotImplementedError('Implement me')
Ejemplo n.º 5
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
Ejemplo n.º 6
0
class Config:

    OUT_EDDN = 1
    OUT_BPC = 2
    OUT_TD = 4
    OUT_CSV = 8
    OUT_SHIP = 16
    OUT_LOG = 32

    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)

            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
            self.bundle = NSBundle.mainBundle().bundleIdentifier()
            self.defaults = NSUserDefaults.standardUserDefaults()
            settings = self.defaults.persistentDomainForName_(self.bundle) or {}
            self.settings = dict(settings)

            # 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):
            return self.settings.get(key)

        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 close(self):
            self.defaults.setPersistentDomain_forName_(self.settings, self.bundle)
            self.defaults.synchronize()
            self.defaults = None

    elif platform == "win32":

        def __init__(self):

            buf = ctypes.create_unicode_buffer(MAX_PATH)
            ctypes.windll.shell32.SHGetSpecialFolderPathW(0, buf, CSIDL_LOCAL_APPDATA, 0)
            self.app_dir = join(buf.value, appname)
            if not isdir(self.app_dir):
                mkdir(self.app_dir)

            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)
                ):
                    SHCopyKey(oldkey, None, self.hkey, 0)
                    SHDeleteKey(oldkey, "")
                    RegCloseKey(oldkey)

                # 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(47 * 60 * 60))
                        RegSetValueEx(sparklekey, "UpdateInterval", 0, 1, buf, len(buf) * 2)
                    RegCloseKey(sparklekey)

            if not self.get("outdir") or not isdir(self.get("outdir")):
                ctypes.windll.shell32.SHGetSpecialFolderPathW(0, buf, CSIDL_PERSONAL, 0)
                self.set("outdir", buf.value)

        def get(self, key):
            typ = DWORD()
            size = DWORD()
            if RegQueryValueEx(self.hkey, key, 0, ctypes.byref(typ), None, ctypes.byref(size)) or typ.value != REG_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
            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)
            else:
                raise NotImplementedError()

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

    elif platform == "linux2":

        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.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("config")

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

        def set(self, key, val):
            self.config.set("config", key, val)

        def get(self, key):
            try:
                return self.config.get("config", key)  # all values are stored as strings
            except:
                return None

        def getint(self, key):
            try:
                return int(self.config.get("config", key))  # all values are stored as strings
            except:
                return 0

        def close(self):
            h = codecs.open(self.filename, "w", "utf-8")
            h.write(unicode(self.config.data))
            h.close()
            self.config = None

    else:  # ???

        def __init__(self):
            raise NotImplementedError("Implement me")
Ejemplo n.º 7
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')
Ejemplo n.º 8
0
class Config:

    OUT_EDDN = 1
    OUT_BPC  = 2
    OUT_TD   = 4
    OUT_CSV  = 8

    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.bundle = getattr(sys, 'frozen', False) and NSBundle.mainBundle().bundleIdentifier() or 'uk.org.marginal.%s' % appname.lower()	# Don't use Python's settings if interactive
            self.defaults = NSUserDefaults.standardUserDefaults()
            settings = self.defaults.persistentDomainForName_(self.bundle) or {}
            self.settings = dict(settings)

            # 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):
            return self.settings.get(key)

        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 close(self):
            self.defaults.setPersistentDomain_forName_(self.settings, self.bundle)
            self.defaults.synchronize()
            self.defaults = None

    elif platform=='win32':

        def __init__(self):
            CSIDL_PERSONAL = 0x0005
            CSIDL_LOCAL_APPDATA = 0x001C
            buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
            ctypes.windll.shell32.SHGetSpecialFolderPathW(0, buf, CSIDL_LOCAL_APPDATA, 0)
            self.app_dir = join(buf.value, appname)
            if not isdir(self.app_dir):
                mkdir(self.app_dir)
            
            self.handle = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, r'Software\%s' % appname)

            if not self.get('outdir') or not isdir(self.get('outdir')):
                ctypes.windll.shell32.SHGetSpecialFolderPathW(0, buf, CSIDL_PERSONAL, 0)
                self.set('outdir', buf.value)

        def get(self, key):
            try:
                return _winreg.QueryValueEx(self.handle, key)[0]
            except:
                return None

        def getint(self, key):
            try:
                return int(_winreg.QueryValueEx(self.handle, key)[0])	# should already be int, but check by casting
            except:
                return 0

        def set(self, key, val):
            if isinstance(val, basestring):
                _winreg.SetValueEx(self.handle, key, 0, _winreg.REG_SZ, val)
            elif isinstance(val, numbers.Integral):
                _winreg.SetValueEx(self.handle, key, 0, _winreg.REG_DWORD, val)
            else:
                raise NotImplementedError()

        def close(self):
            _winreg.CloseKey(self.handle)
            self.handle = None

    elif platform=='linux2':

        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.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'))
                # XXX handle missing?
            except:
                self.config.add_section('DEFAULT')

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

        def set(self, key, val):
            self.config.set('DEFAULT', key, val)

        def get(self, key):
            try:
                return self.config.get('DEFAULT', key)	# all values are stored as strings
            except:
                return None

        def getint(self, key):
            try:
                return int(self.config.get('DEFAULT', key))	# all values are stored as strings
            except:
                return 0

        def close(self):
            h = codecs.open(self.filename, 'w', 'utf-8')
            h.write(unicode(self.config.data))
            h.close()
            self.config = None

    else:	# ???

        def __init__(self):
            raise NotImplementedError('Implement me')
Ejemplo n.º 9
0
def main():
    if len(args) == 0:
        print "ERROR : You must provide one action to perform"
        parser.print_usage()
        sys.exit(2)

    action = args[0]

    # Config file
    if not os.path.isfile(config_file):
        logger.error("Error : could not find file : " + config_file + ", please check the path")

    logger.debug("Config file: %s" % config_file)

    defaults = {
        "repositories": "",
        "repo_url": "",
        "default_source_url": "",
        "private_key": "",
        "public_cert": "",
        "default_development_base": "c:\tranquilit",
        "default_package_prefix": "tis",
        "default_sources_suffix": "wapt",
        "default_sources_url": "",
        "upload_cmd": "",
        "wapt_server": "",
        "loglevel": "info",
    }

    cp = RawConfigParser(defaults=defaults)
    cp.add_section("global")
    cp.read(config_file)

    global loglevel
    if not loglevel and cp.has_option("global", "loglevel"):
        loglevel = cp.get("global", "loglevel")
        setloglevel(loglevel)

    mywapt = Wapt(config=cp)
    if options.wapt_url:
        mywapt.wapt_repourl = options.wapt_url

    if options.private_key:
        mywapt.private_key = options.private_key
    else:
        mywapt.private_key = cp.get("global", "private_key")

    mywapt.dry_run = options.dry_run
    # logger.info("Main wapt Repository %s" % mywapt.wapt_repourl)
    logger.debug("WAPT base directory : %s" % mywapt.wapt_base_dir)
    logger.debug("Package cache dir : %s" % mywapt.packagecachedir)
    logger.debug("WAPT DB Structure version;: %s" % mywapt.waptdb.db_version)

    try:
        params_dict = {}
        try:
            params_dict = json.loads(options.params.replace("'", '"'))
        except:
            raise Exception("Install Parameters must be in json format")

        if action == "install" or action == "download":
            if len(args) < 2:
                print "You must provide at least one package name"
                sys.exit(1)

            if os.path.isdir(args[1]) or os.path.isfile(args[1]):
                print "installing WAPT file %s" % args[1]
                if action == "install":
                    mywapt.install_wapt(args[1], params_dict=params_dict)
            else:
                print "%sing WAPT packages %s" % (action, ",".join(args[1:]))
                if options.update_packages:
                    print "Update package list"
                    mywapt.update()

                result = mywapt.install(
                    args[1:], force=options.force, params_dict=params_dict, download_only=(action == "download")
                )
                print "\nResults :"
                if action <> "download":
                    for k in ("install", "additional", "upgrade", "skipped", "errors"):
                        if result.get(k, []):
                            print "\n=== %s packages ===\n%s" % (
                                k,
                                "\n".join(
                                    ["  %-30s | %s (%s)" % (s[0], s[1].package, s[1].version) for s in result[k]]
                                ),
                            )
                else:
                    for k in ("downloaded", "skipped", "errors"):
                        if result.get("downloads", {"downloaded": [], "skipped": [], "errors": []})[k]:
                            print "\n=== %s packages ===\n%s" % (
                                k,
                                "\n".join(["  %s" % (s,) for s in result["downloads"][k]]),
                            )

        elif action == "download":
            if len(args) < 2:
                print "You must provide at least one package name to download"
                sys.exit(1)
            if options.update_packages:
                print "Update package list"
                mywapt.update()
            print "Downloading packages %s" % (",".join(args[1:]),)
            result = mywapt.download_packages(args[1:], usecache=not options.force)
            if result["downloaded"]:
                print "\nDownloaded packages : \n%s" % "\n".join(["  %s" % p for p in result["downloaded"]])
            if result["skipped"]:
                print "Skipped packages : \n%s" % "\n".join(["  %s" % p for p in result["skipped"]])
            if result["errors"]:
                logger.critical("Unable to download some files : %s" % (result["errors"],))
                sys.exit(1)

        elif action == "show":
            if len(args) < 2:
                print "You must provide at least one package name to show"
                sys.exit(1)
            if os.path.isdir(args[1]) or os.path.isfile(args[1]):
                entry = PackageEntry().load_control_from_wapt(args[1])
                print "%s" % entry
            else:
                print "Display package control data for %s\n" % (",".join(args[1:]),)
                if options.update_packages:
                    print "Update package list"
                    mywapt.update()
                for packagename in args[1:]:
                    entries = mywapt.waptdb.packages_matching(packagename)
                    if entries:
                        for e in entries:
                            print "%s\n" % e.ascontrol(with_non_control_attributes=True)
                    else:
                        print "None packages found matching package name and version"
        elif action == "show-params":
            if len(args) < 2:
                print "You must provide at one package name to show params for"
                sys.exit(1)
            for packagename in args[1:]:
                params = mywapt.waptdb.params(packagename)
                print "%s" % params

        elif action == "list-registry":
            print "%-39s%-70s%-20s%-70s" % ("UninstallKey", "Software", "Version", "Uninstallstring")
            print "-" * 39 + "-" * 70 + "-" * 20 + "-" * 70
            for p in setuphelpers.installed_softwares(" ".join(args[1:])):
                print u"%-39s%-70s%-20s%-70s" % (p["key"], p["name"], p["version"], p["uninstall_string"])

        elif action == "showlog":
            if len(args) < 2:
                print "You must provide at least one package name"
                sys.exit(1)
            for packagename in args[1:]:
                result = mywapt.last_install_log(packagename)
                print "Package : %s\nStatus : %s\n\nInstallation log:\n%s" % (
                    packagename,
                    result["status"],
                    result["log"],
                )

        elif action == "remove":
            if len(args) < 2:
                print "You must provide at least one package name to remove"
                sys.exit(1)
            for packagename in args[1:]:
                print "Removing %s ..." % (packagename,),
                mywapt.remove(packagename, force=options.force)
                print "done"

        elif action == "session-setup":
            if len(args) < 2:
                print "You must provide at least one package to be configured in user's session"
                sys.exit(1)

            for packagename in args[1:]:
                print "Configuring %s ..." % (packagename,),
                mywapt.session_setup(packagename, params_dict=params_dict)
                print "done"

        elif action == "uninstall":
            # launch the setup.uninstall() procedure for the given packages
            # can be used when registering in registry a custom install with a python script
            if len(args) < 2:
                print "You must provide at least one package to be uninstalled"
                sys.exit(1)

            for packagename in args[1:]:
                print "uninstalling %s ..." % (packagename,),
                mywapt.uninstall(packagename, params_dict=params_dict)
                print "uninstall done"

        elif action == "update":
            print "Update package list"
            result = mywapt.update()
            print "Total packages : %i" % result["count"]
            print "Added packages : \n%s" % "\n".join(["  %s (%s)" % p for p in result["added"]])
            print "Removed packages : \n%s" % "\n".join(["  %s (%s)" % p for p in result["removed"]])
            print "Repositories URL : \n%s" % "\n".join(["  %s" % p for p in result["repos"]])

        elif action == "upgradedb":
            (old, new) = mywapt.waptdb.upgradedb()
            if old == new:
                print "No database upgrade required, current %s, required %s" % (old, mywapt.waptdb.curr_db_version)
            else:
                print "Old version : %s to new : %s" % (old, new)

        elif action == "upgrade":
            if options.update_packages:
                print "Update package list"
                mywapt.update()
            result = mywapt.upgrade()
            if not result["install"] and not result["additional"] and not result["upgrade"] and not result["skipped"]:
                print "Nothing to upgrade"
            else:
                for k in ("install", "additional", "upgrade", "skipped", "errors"):
                    if result[k]:
                        print "\n=== %s packages ===\n%s" % (
                            k,
                            "\n".join(["  %-30s | %s (%s)" % (s[0], s[1].package, s[1].version) for s in result[k]]),
                        )

            sys.exit(0)

        elif action == "list-upgrade":
            if options.update_packages:
                print "Update package list"
                mywapt.update()
            q = mywapt.list_upgrade()
            if not q:
                print "Nothing to upgrade"
            else:
                print ppdicttable([p[0] for p in q], [("package", 20), ("version", 10)])

        elif action == "download-upgrade":
            if options.update_packages:
                print "Update package list"
                mywapt.update()
            result = mywapt.download_upgrades()
            print "Downloaded packages : \n%s" % "\n".join(["  %s" % p for p in result["downloaded"]])
            print "Skipped packages : \n%s" % "\n".join(["  %s" % p for p in result["skipped"]])

            if result["errors"]:
                logger.critical("Unable to download some files : %s" % (result["errors"],))
                sys.exit(1)

        elif action == "update-packages":
            if len(args) < 2:
                print "You must provide the directory"
                sys.exit(1)
            print update_packages(args[1])

        elif action == "sources":
            if len(args) < 2:
                print "You must provide the package name"
                sys.exit(1)
            os.startfile(mywapt.get_sources(args[1]))

        elif action == "make-template":
            if len(args) < 2:
                print "You must provide the installer path"
                sys.exit(1)
            source_dir = mywapt.maketemplate(*args[1:])
            print "Template created. You can build the WAPT package by launching\n  %s build-package %s" % (
                sys.argv[0],
                source_dir,
            )
            os.startfile(source_dir)

        elif action == "make-host-template":
            source_dir = mywapt.makehosttemplate(*args[1:])
            print "Template created. You can build the WAPT package by launching\n  %s build-package %s" % (
                sys.argv[0],
                source_dir,
            )
            os.startfile(source_dir)

        elif action == "build-package":
            if len(args) < 2:
                print "You must provide at least one source directory for package build"
                sys.exit(1)
            for source_dir in [os.path.abspath(p) for p in args[1:]]:
                if os.path.isdir(source_dir):
                    print ("Building  %s" % source_dir)
                    result = mywapt.buildpackage(
                        source_dir, inc_package_release=options.increlease, excludes=options.excludes.split(",")
                    )
                    package_fn = result["filename"]
                    if package_fn:
                        print "Package content:"
                        for f in result["files"]:
                            print " %s" % f[0]
                        print ("...done. Package filename %s" % (package_fn,))

                        def pwd_callback(*args):
                            """Default password callback for opening private keys"""
                            return open(options.private_key_passwd, "r").read()

                        if mywapt.private_key:
                            print ("Signing %s" % package_fn)
                            if options.private_key_passwd:
                                signature = mywapt.signpackage(
                                    package_fn, excludes=options.excludes.split(","), callback=pwd_callback
                                )
                            else:
                                signature = mywapt.signpackage(package_fn, excludes=options.excludes.split(","))
                            print "Package %s signed : signature :\n%s" % (package_fn, signature)
                        else:
                            logger.warning("No private key provided, package %s is unsigned !" % package_fn)

                        if mywapt.upload_cmd:
                            print "\nYou can upload to repository with\n  %s upload-package %s " % (
                                sys.argv[0],
                                package_fn,
                            )
                        return 0
                    else:
                        logger.critical("package not created")
                        return 1
                else:
                    logger.critical("Directory %s not found" % source_dir)

        elif action == "sign-package":
            if len(args) < 2:
                print "You must provide at least one source directory or package to sign"
                sys.exit(1)
            for waptfile in [os.path.abspath(p) for p in args[1:]]:
                if os.path.isdir(waptfile) or os.path.isfile(waptfile):
                    print ("Signing %s" % waptfile)
                    signature = mywapt.signpackage(waptfile, excludes=options.excludes.split(","))
                    print "Package %s signed : signature :\n%s" % (waptfile, signature)
                else:
                    logger.critical("Package %s not found" % waptfile)
                    return 1

        elif action == "upload-package":
            if len(args) < 2:
                print "You must provide a package to upload"
                sys.exit(1)
            waptfiles = []
            for a in args[1:]:
                waptfiles += glob.glob(a)
            waptfile_arg = " ".join(['"%s"' % f for f in waptfiles])
            print setuphelpers.run(mywapt.upload_cmd % {"waptfile": waptfile_arg})
            if mywapt.after_upload:
                print setuphelpers.run(mywapt.after_upload % {"waptfile": waptfile_arg})

        elif action == "search":
            if options.update_packages:
                print "Update package list"
                mywapt.update()
            result = mywapt.waptdb.packages_search(args[1:])
            print ppdicttable(result, (("package", 30), ("version", 10), ("description", 80)))

        elif action == "cleanup":
            result = mywapt.cleanup()
            print "Removed files : \n%s" % "\n".join(["  %s" % p for p in result])

        elif action == "inventory":
            print mywapt.inventory()

        elif action == "setup-tasks":
            print mywapt.setup_tasks()

        elif action == "list":

            def cb(fieldname, value):
                if value and fieldname == "install_date":
                    return value[0:16]
                else:
                    return value

            print ppdicttable(
                mywapt.waptdb.installed_search(args[1:]).values(),
                (("package", 20), ("version", 15), ("install_status", 10), ("install_date", 16), ("description", 80)),
                callback=cb,
            )
        else:
            print "Unknown action %s" % action
            sys.exit(1)
    except Exception, e:
        print "FATAL ERROR : %s" % e
        if logger.level == logging.DEBUG:
            raise
        sys.exit(3)
Ejemplo n.º 10
0
sbuild_arch = get_sbuild_architecture()
if args.sbuild_path is None:
    if not args.base_directory:
        parser.print_usage()
        parser.exit()
    sbuild_path = os.path.join(args.base_directory, config.distribution.chroot)
else:
    sbuild_path = args.sbuild_path

if args.remove_old:
    for entry in os.scandir('/etc/schroot/chroot.d'):
        cp = RawConfigParser()
        cp.read([entry.path])
        if config.distribution.chroot in cp.sections():
            old_sbuild_path = cp.get('unstable-amd64-sbuild', 'directory')
            if old_sbuild_path != sbuild_path:
                raise AssertionError('sbuild path has changed: %s != %s' %
                                     (old_sbuild_path, sbuild_path))
            if os.path.isdir(old_sbuild_path):
                shutil.rmtree(old_sbuild_path)
            os.unlink(entry.path)

create_chroot(config.distribution,
              sbuild_path,
              config.suite,
              sbuild_arch,
              args.include,
              make_sbuild_tarball=args.make_sbuild_tarball)

if args.user:
Ejemplo n.º 11
0
def main():
    if len(args) == 0:
        print "ERROR : You must provide one action to perform"
        parser.print_usage()
        sys.exit(2)

    action = args[0]

    # Config file
    if not os.path.isfile(config_file):
        logger.error("Error : could not find file : " + config_file +
                     ", please check the path")

    logger.debug('Config file: %s' % config_file)

    defaults = {
        'repositories': '',
        'repo_url': '',
        'default_source_url': '',
        'private_key': '',
        'public_cert': '',
        'default_development_base': 'c:\tranquilit',
        'default_package_prefix': 'tis',
        'default_sources_suffix': 'wapt',
        'default_sources_url': '',
        'upload_cmd': '',
        'wapt_server': '',
        'loglevel': 'info',
    }

    cp = RawConfigParser(defaults=defaults)
    cp.add_section('global')
    cp.read(config_file)

    global loglevel
    if not loglevel and cp.has_option('global', 'loglevel'):
        loglevel = cp.get('global', 'loglevel')
        setloglevel(loglevel)

    mywapt = Wapt(config=cp)
    if options.wapt_url:
        mywapt.wapt_repourl = options.wapt_url

    if options.private_key:
        mywapt.private_key = options.private_key
    else:
        mywapt.private_key = cp.get('global', 'private_key')

    mywapt.dry_run = options.dry_run
    #logger.info("Main wapt Repository %s" % mywapt.wapt_repourl)
    logger.debug('WAPT base directory : %s' % mywapt.wapt_base_dir)
    logger.debug('Package cache dir : %s' % mywapt.packagecachedir)
    logger.debug('WAPT DB Structure version;: %s' % mywapt.waptdb.db_version)

    try:
        params_dict = {}
        try:
            params_dict = json.loads(options.params.replace("'", '"'))
        except:
            raise Exception('Install Parameters must be in json format')

        if action == 'install' or action == 'download':
            if len(args) < 2:
                print "You must provide at least one package name"
                sys.exit(1)

            if os.path.isdir(args[1]) or os.path.isfile(args[1]):
                print "installing WAPT file %s" % args[1]
                if action == 'install':
                    mywapt.install_wapt(args[1], params_dict=params_dict)
            else:
                print "%sing WAPT packages %s" % (action, ','.join(args[1:]))
                if options.update_packages:
                    print "Update package list"
                    mywapt.update()

                result = mywapt.install(
                    args[1:],
                    force=options.force,
                    params_dict=params_dict,
                    download_only=(action == 'download'),
                )
                print "\nResults :"
                if action <> 'download':
                    for k in ('install', 'additional', 'upgrade', 'skipped',
                              'errors'):
                        if result.get(k, []):
                            print "\n=== %s packages ===\n%s" % (
                                k,
                                '\n'.join([
                                    "  %-30s | %s (%s)" %
                                    (s[0], s[1].package, s[1].version)
                                    for s in result[k]
                                ]),
                            )
                else:
                    for k in ('downloaded', 'skipped', 'errors'):
                        if result.get('downloads', {
                                'downloaded': [],
                                'skipped': [],
                                'errors': []
                        })[k]:
                            print "\n=== %s packages ===\n%s" % (
                                k,
                                '\n'.join([
                                    "  %s" % (s, )
                                    for s in result['downloads'][k]
                                ]),
                            )

        elif action == 'download':
            if len(args) < 2:
                print "You must provide at least one package name to download"
                sys.exit(1)
            if options.update_packages:
                print "Update package list"
                mywapt.update()
            print "Downloading packages %s" % (','.join(args[1:]), )
            result = mywapt.download_packages(args[1:],
                                              usecache=not options.force)
            if result['downloaded']:
                print "\nDownloaded packages : \n%s" % "\n".join(
                    ["  %s" % p for p in result['downloaded']])
            if result['skipped']:
                print "Skipped packages : \n%s" % "\n".join(
                    ["  %s" % p for p in result['skipped']])
            if result['errors']:
                logger.critical('Unable to download some files : %s' %
                                (result['errors'], ))
                sys.exit(1)

        elif action == 'show':
            if len(args) < 2:
                print "You must provide at least one package name to show"
                sys.exit(1)
            if os.path.isdir(args[1]) or os.path.isfile(args[1]):
                entry = PackageEntry().load_control_from_wapt(args[1])
                print "%s" % entry
            else:
                print "Display package control data for %s\n" % (','.join(
                    args[1:]), )
                if options.update_packages:
                    print "Update package list"
                    mywapt.update()
                for packagename in args[1:]:
                    entries = mywapt.waptdb.packages_matching(packagename)
                    if entries:
                        for e in entries:
                            print "%s\n" % e.ascontrol(
                                with_non_control_attributes=True)
                    else:
                        print "None packages found matching package name and version"
        elif action == 'show-params':
            if len(args) < 2:
                print "You must provide at one package name to show params for"
                sys.exit(1)
            for packagename in args[1:]:
                params = mywapt.waptdb.params(packagename)
                print "%s" % params

        elif action == 'list-registry':
            print "%-39s%-70s%-20s%-70s" % ('UninstallKey', 'Software',
                                            'Version', 'Uninstallstring')
            print '-' * 39 + '-' * 70 + '-' * 20 + '-' * 70
            for p in setuphelpers.installed_softwares(' '.join(args[1:])):
                print u"%-39s%-70s%-20s%-70s" % (
                    p['key'], p['name'], p['version'], p['uninstall_string'])

        elif action == 'showlog':
            if len(args) < 2:
                print "You must provide at least one package name"
                sys.exit(1)
            for packagename in args[1:]:
                result = mywapt.last_install_log(packagename)
                print "Package : %s\nStatus : %s\n\nInstallation log:\n%s" % (
                    packagename, result['status'], result['log'])

        elif action == 'remove':
            if len(args) < 2:
                print "You must provide at least one package name to remove"
                sys.exit(1)
            for packagename in args[1:]:
                print "Removing %s ..." % (packagename, ),
                mywapt.remove(packagename, force=options.force)
                print "done"

        elif action == 'session-setup':
            if len(args) < 2:
                print "You must provide at least one package to be configured in user's session"
                sys.exit(1)

            for packagename in args[1:]:
                print "Configuring %s ..." % (packagename, ),
                mywapt.session_setup(packagename, params_dict=params_dict)
                print "done"

        elif action == 'uninstall':
            # launch the setup.uninstall() procedure for the given packages
            # can be used when registering in registry a custom install with a python script
            if len(args) < 2:
                print "You must provide at least one package to be uninstalled"
                sys.exit(1)

            for packagename in args[1:]:
                print "uninstalling %s ..." % (packagename, ),
                mywapt.uninstall(packagename, params_dict=params_dict)
                print "uninstall done"

        elif action == 'update':
            print "Update package list"
            result = mywapt.update()
            print "Total packages : %i" % result['count']
            print "Added packages : \n%s" % "\n".join(
                ["  %s (%s)" % p for p in result['added']])
            print "Removed packages : \n%s" % "\n".join(
                ["  %s (%s)" % p for p in result['removed']])
            print "Repositories URL : \n%s" % "\n".join(
                ["  %s" % p for p in result['repos']])

        elif action == 'upgradedb':
            (old, new) = mywapt.waptdb.upgradedb()
            if old == new:
                print "No database upgrade required, current %s, required %s" % (
                    old, mywapt.waptdb.curr_db_version)
            else:
                print "Old version : %s to new : %s" % (old, new)

        elif action == 'upgrade':
            if options.update_packages:
                print "Update package list"
                mywapt.update()
            result = mywapt.upgrade()
            if not result['install'] and not result[
                    'additional'] and not result['upgrade'] and not result[
                        'skipped']:
                print "Nothing to upgrade"
            else:
                for k in ('install', 'additional', 'upgrade', 'skipped',
                          'errors'):
                    if result[k]:
                        print "\n=== %s packages ===\n%s" % (
                            k,
                            '\n'.join([
                                "  %-30s | %s (%s)" %
                                (s[0], s[1].package, s[1].version)
                                for s in result[k]
                            ]),
                        )

            sys.exit(0)

        elif action == 'list-upgrade':
            if options.update_packages:
                print "Update package list"
                mywapt.update()
            q = mywapt.list_upgrade()
            if not q:
                print "Nothing to upgrade"
            else:
                print ppdicttable([p[0] for p in q], [('package', 20),
                                                      ('version', 10)])

        elif action == 'download-upgrade':
            if options.update_packages:
                print "Update package list"
                mywapt.update()
            result = mywapt.download_upgrades()
            print "Downloaded packages : \n%s" % "\n".join(
                ["  %s" % p for p in result['downloaded']])
            print "Skipped packages : \n%s" % "\n".join(
                ["  %s" % p for p in result['skipped']])

            if result['errors']:
                logger.critical('Unable to download some files : %s' %
                                (result['errors'], ))
                sys.exit(1)

        elif action == 'update-packages':
            if len(args) < 2:
                print "You must provide the directory"
                sys.exit(1)
            print update_packages(args[1])

        elif action == 'sources':
            if len(args) < 2:
                print "You must provide the package name"
                sys.exit(1)
            os.startfile(mywapt.get_sources(args[1]))

        elif action == 'make-template':
            if len(args) < 2:
                print "You must provide the installer path"
                sys.exit(1)
            source_dir = mywapt.maketemplate(*args[1:])
            print "Template created. You can build the WAPT package by launching\n  %s build-package %s" % (
                sys.argv[0], source_dir)
            os.startfile(source_dir)

        elif action == 'make-host-template':
            source_dir = mywapt.makehosttemplate(*args[1:])
            print "Template created. You can build the WAPT package by launching\n  %s build-package %s" % (
                sys.argv[0], source_dir)
            os.startfile(source_dir)

        elif action == 'build-package':
            if len(args) < 2:
                print "You must provide at least one source directory for package build"
                sys.exit(1)
            for source_dir in [os.path.abspath(p) for p in args[1:]]:
                if os.path.isdir(source_dir):
                    print('Building  %s' % source_dir)
                    result = mywapt.buildpackage(
                        source_dir,
                        inc_package_release=options.increlease,
                        excludes=options.excludes.split(','))
                    package_fn = result['filename']
                    if package_fn:
                        print "Package content:"
                        for f in result['files']:
                            print " %s" % f[0]
                        print('...done. Package filename %s' % (package_fn, ))

                        def pwd_callback(*args):
                            """Default password callback for opening private keys"""
                            return open(options.private_key_passwd, 'r').read()

                        if mywapt.private_key:
                            print('Signing %s' % package_fn)
                            if options.private_key_passwd:
                                signature = mywapt.signpackage(
                                    package_fn,
                                    excludes=options.excludes.split(','),
                                    callback=pwd_callback)
                            else:
                                signature = mywapt.signpackage(
                                    package_fn,
                                    excludes=options.excludes.split(','))
                            print "Package %s signed : signature :\n%s" % (
                                package_fn, signature)
                        else:
                            logger.warning(
                                'No private key provided, package %s is unsigned !'
                                % package_fn)

                        if mywapt.upload_cmd:
                            print '\nYou can upload to repository with\n  %s upload-package %s ' % (
                                sys.argv[0], package_fn)
                        return 0
                    else:
                        logger.critical('package not created')
                        return 1
                else:
                    logger.critical('Directory %s not found' % source_dir)

        elif action == 'sign-package':
            if len(args) < 2:
                print "You must provide at least one source directory or package to sign"
                sys.exit(1)
            for waptfile in [os.path.abspath(p) for p in args[1:]]:
                if os.path.isdir(waptfile) or os.path.isfile(waptfile):
                    print('Signing %s' % waptfile)
                    signature = mywapt.signpackage(
                        waptfile, excludes=options.excludes.split(','))
                    print "Package %s signed : signature :\n%s" % (waptfile,
                                                                   signature)
                else:
                    logger.critical('Package %s not found' % waptfile)
                    return 1

        elif action == 'upload-package':
            if len(args) < 2:
                print "You must provide a package to upload"
                sys.exit(1)
            waptfiles = []
            for a in args[1:]:
                waptfiles += glob.glob(a)
            waptfile_arg = " ".join(['"%s"' % f for f in waptfiles])
            print setuphelpers.run(mywapt.upload_cmd %
                                   {'waptfile': waptfile_arg})
            if mywapt.after_upload:
                print setuphelpers.run(mywapt.after_upload %
                                       {'waptfile': waptfile_arg})

        elif action == 'search':
            if options.update_packages:
                print "Update package list"
                mywapt.update()
            result = mywapt.waptdb.packages_search(args[1:])
            print ppdicttable(result, (('package', 30), ('version', 10),
                                       ('description', 80)))

        elif action == 'cleanup':
            result = mywapt.cleanup()
            print "Removed files : \n%s" % "\n".join(
                ["  %s" % p for p in result])

        elif action == 'inventory':
            print mywapt.inventory()

        elif action == 'setup-tasks':
            print mywapt.setup_tasks()

        elif action == 'list':

            def cb(fieldname, value):
                if value and fieldname == 'install_date':
                    return value[0:16]
                else:
                    return value

            print ppdicttable(
                mywapt.waptdb.installed_search(args[1:]).values(),
                (('package', 20), ('version', 15), ('install_status', 10),
                 ('install_date', 16), ('description', 80)),
                callback=cb)
        else:
            print 'Unknown action %s' % action
            sys.exit(1)
    except Exception, e:
        print "FATAL ERROR : %s" % e
        if logger.level == logging.DEBUG:
            raise
        sys.exit(3)