summaryrefslogtreecommitdiff
path: root/portato/session.py
blob: 0bafee27b7f01fb4c1aaa4cc4b2c9cfe9eb80899 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# -*- coding: utf-8 -*-
#
# File: portato/session.py
# This file is part of the Portato-Project, a graphical portage-frontend.
#
# Copyright (C) 2007-2009 René 'Necoro' Neumann
# This is free software.  You may redistribute copies of it under the terms of
# the GNU General Public License version 2.
# There is NO WARRANTY, to the extent permitted by law.
#
# Written by René 'Necoro' Neumann <necoro@necoro.net>

from __future__ import absolute_import, with_statement

import os, os.path

from .config_parser import ConfigParser, SectionNotFoundException
from .constants import SESSION_DIR
from .helper import debug, info

sessionlist = []

class Session (object):
    """
    A small class allowing to save certain states of a program.
    This class works in a quite abstract manner, as it works with handlers, which
    define what options to use out of the config file and how to apply them to the program.

    Note: This class currently does not work with boolean config options. If you
    want to define boolean values, use 0 and 1. This is future proof.
    """

    # the current session format version
    VERSION = 1

    def __init__ (self, file, name="", oldfiles = [], register = True):
        """
        Initialize a session with a certain file inside L{SESSION_DIR}.

        @param file: the file in L{SESSION_DIR}, where the options will be saved.
        @param oldfiles: old file names for the same file
        @param name: short name describing the type of session
        @param register: register in the global sessionlist, which is closed at the end
        """

        self._cfg = None
        self._handlers = []
        self._name = name if name else "MAIN"

        if not (os.path.exists(SESSION_DIR) and os.path.isdir(SESSION_DIR)):
            os.mkdir(SESSION_DIR)

        file = os.path.join(SESSION_DIR, file)
        oldfiles = [os.path.join(SESSION_DIR, x) for x in oldfiles]

        if not os.path.exists(file):
            for o in oldfiles:
                if os.path.exists(o):
                    debug("Moving old session file '%s' to '%s'." % (o, file))
                    os.rename(o,file)
                    break

        self._cfg = ConfigParser(file)

        if name:
            i = _("Loading '%s' session from %s.") % (name, self._cfg.file)
        else:
            i = _("Loading session from %s.") % self._cfg.file

        info(i)

        try:
            self._cfg.parse()
        except IOError, e:
            if e.errno == 2: pass
            else: raise

        # register
        if register: sessionlist.append(self)

        # add version check
        self.add_handler(([("version", "session")], self.check_version, lambda: self.VERSION))

    def add_handler (self, (options, load_fn, save_fn), default = None):
        """
        Adds a handler to this session. A handler is a three-tuple consisting of:
            - a list of (key,section) values
            - a function getting number of option arguments and applying them to the program
            - a function returning the number of option return values - getting them out of the program
        """

        options = map(lambda x: (x, self._name) if not hasattr(x, "__iter__") else x, options)
        self._handlers.append((options, load_fn, save_fn, default))

    def load (self, defaults_only = False):
        """
        Loads and applies all values of the session.
        """
        
        def ldefault (options, lfn, default):
            if not default: return
            debug("Loading %s with defaults %s.", options, default)
            lfn(*default)

        for options, lfn, sfn, default in self._handlers:
            if defaults_only:
                ldefault(options, lfn, default)
            else:
                try:
                    loaded = [self._cfg.get(*x) for x in options]
                except KeyError: # does not exist -> ignore
                    debug("No values for %s.", options)
                    ldefault(options, lfn, default)
                else:
                    debug("Loading %s with values %s.", options, loaded)
                    lfn(*loaded)

    def save (self):
        """
        Saves all options into the file.
        """

        for options, lfn, sfn, default in self._handlers:
            vals = sfn()
            
            # map into list if necessairy
            if not hasattr(vals, "__iter__"):
                vals = [vals]
            debug("Saving %s with values %s", options, vals)

            for value, (option, section) in zip(vals, options):
                self.set(option, str(value), section)
        
        self._cfg.write()

    @classmethod
    def close (cls):
        for s in sessionlist:
            if s._name != "MAIN":
                info(_("Saving '%s' session to %s.") % (s._name, s._cfg.file))
            else:
                info(_("Saving session to %s.") % s._cfg.file)
            s.save()

    def set (self, key, value, section = ""):
        if not section: section = self._name

        try:
            self._cfg.add(key, value, section, with_blankline = False)
        except SectionNotFoundException:
            self._cfg.add_section(section)
            self._cfg.add(key, value, section, with_blankline = False)
    
    def get (self, key, section = ""):
        if not section: section = self._name

        try:
            return self._cfg.get(key, section)
        except KeyError:
            return None
    
    def get_boolean (self, key, section = ""):
        if not section: section = self._name

        try:
            return self._cfg.get_boolean(key, section)
        except KeyError:
            return None

    def remove (self, key, section = ""):
        if not section: section = self._name

        section = section.upper()
        key = key.lower()

        val = self._cfg._access(key, section)
        del self._cfg.cache[val.line]

        self._cfg.write()

    def remove_section (self, section):
        section = section.upper()

        sline = self._cfg.sections[section]

        try:
            mline = max(v.line for v in self._cfg.vars[section].itervalues())
        except ValueError: # nothing in the section
            mline = sline
        
        sline = max(sline - 1, 0) # remove blank line too - but only if there is one ;)

        del self._cfg.cache[sline:mline+1]
        self._cfg.write()

    def rename (self, old, new, section = ""):
        if not section: section = self._name
        
        val = self.get(old, section)
        self.remove(old, section)
        self._cfg.add(new, val, section, with_blankline = False)

    def rename_section (self, old, new):
        old = old.upper()
        line = self._cfg.sections[old]
        self._cfg.cache[line] = "[%s]\n" % new.upper()
        self._cfg.write()

    def check_version (self, vers):
        pass # do nothing atm