Use exceptions for error handling
[rarslave2.git] / rsutil / config.py
1 #!/usr/bin/env python
2 # vim: set ts=4 sts=4 sw=4 textwidth=92:
3
4 """
5 Module holding the config class, to be used by the rarslave project.
6 """
7
8 __author__    = "Ira W. Snyder (devel@irasnyder.com)"
9 __copyright__ = "Copyright (c) 2006,2007 Ira W. Snyder (devel@irasnyder.com)"
10 __license__   = "GNU GPL v2 (or, at your option, any later version)"
11
12 #    config.py -- configuration class for rarslave
13 #
14 #    Copyright (C) 2006,2007  Ira W. Snyder (devel@irasnyder.com)
15 #
16 #    This program is free software; you can redistribute it and/or modify
17 #    it under the terms of the GNU General Public License as published by
18 #    the Free Software Foundation; either version 2 of the License, or
19 #    (at your option) any later version.
20 #
21 #    This program is distributed in the hope that it will be useful,
22 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
23 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 #    GNU General Public License for more details.
25 #
26 #    You should have received a copy of the GNU General Public License
27 #    along with this program; if not, write to the Free Software
28 #    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
29
30 import os, ConfigParser
31
32 class config (object):
33         """A simple class to hold the default configs for the whole program"""
34
35         DEFAULT_CONFIG=os.path.join ('~','.config','rarslave2','rarslave2.conf')
36
37         def __read_config(self, filename=DEFAULT_CONFIG):
38                 """Attempt to open and read the rarslave config file"""
39
40                 # Make sure the filename is corrected
41                 filename = os.path.abspath(os.path.expanduser(filename))
42
43                 user_config = {}
44
45                 # Write the default config if it doesn't exist
46                 if not os.path.isfile(filename):
47                         self.write_config(default=True)
48
49                 config = ConfigParser.ConfigParser()
50                 config.read(filename)
51
52                 for section in config.sections():
53                         for option in config.options(section):
54                                 user_config[(section, option)] = config.get(section, option)
55
56                 return user_config
57
58         def write_config(self, filename=DEFAULT_CONFIG, default=False):
59                 """Write out the current config to the config file. If you set default=True, then
60                 the default config file will be written."""
61
62                 config = ConfigParser.ConfigParser()
63
64                 # Correct filename
65                 filename = os.path.abspath(os.path.expanduser(filename))
66
67                 # Reset all config to make sure we write the default one, if necessary
68                 if default:
69                         self.__user_config = {}
70                         print 'Writing default config to %s' % (filename, )
71
72                 # [directories] section
73                 config.add_section('directories')
74                 for (s, k) in self.__defaults.keys():
75                         if s == 'directories':
76                                 config.set(s, k, self.get_value(s, k))
77
78                 # [options] section
79                 config.add_section('options')
80                 for (s, k) in self.__defaults.keys():
81                         if s == 'options':
82                                 config.set(s, k, self.get_value(s, k))
83
84                 # [regular_expressions] section
85                 config.add_section('regular expressions')
86                 for (s, k) in self.__defaults.keys():
87                         if s == 'regular expressions':
88                                 config.set(s, k, self.get_value(s, k))
89
90                 # [commands] section
91                 config.add_section('commands')
92                 for (s, k) in self.__defaults.keys():
93                         if s == 'commands':
94                                 config.set(s, k, self.get_value(s, k))
95
96                 # Try to make the ~/.config/rarslave/ directory
97                 if not os.path.isdir(os.path.split(filename)[0]):
98                         try:
99                                 os.makedirs(os.path.split(filename)[0])
100                         except:
101                                 print 'Could not make directory: %s' % (os.path.split(filename)[0], )
102                                 sys.exit()
103
104                 # Try to write the config file to disk
105                 try:
106                         fsock = open(filename, 'w')
107                         try:
108                                 config.write(fsock)
109                         finally:
110                                 fsock.close()
111                 except:
112                         print 'Could not open: %s for writing' % (filename, )
113                         sys.exit()
114
115         def __get_default_val(self, section, key):
116                 return self.__defaults[(section, key)]
117
118         def get_value(self, section, key):
119                 """Get a config value. Attempts to get the value from the user's
120                 config first, and then uses the default."""
121
122                 try:
123                         value = self.__user_config[(section, key)]
124                 except:
125                         # This should work, unless you write something stupid
126                         # into the code, so DON'T DO IT
127                         value = self.__get_default_val(section, key)
128
129                 # Convert config options to native types for easier use
130                 SAFE_EVAL = ['None', 'True', 'False', '-1', '0', '1', '2']
131
132                 if value in SAFE_EVAL:
133                         value = eval (value)
134
135                 # Absolute-ize directories for easier use
136                 if section == 'directories' and value != None:
137                         value = os.path.abspath (os.path.expanduser (value))
138
139                 return value
140
141         def __init__(self):
142                 self.__defaults = {
143                         ('directories', 'working_directory') : os.path.join ('~','downloads','usenet'),
144                         ('directories', 'extract_directory') : None,
145                         ('options', 'recursive') : True,
146                         ('options', 'interactive') : False,
147                         ('options', 'output_loglevel') : 0,
148                         ('regular expressions', 'par2_regex') : '^.*\.par2$',
149                         ('regular expressions', 'delete_regex') :
150                                         '^.*\.(par2|\d|\d\d\d|rar|r\d\d|zip)$',
151                         ('regular expressions', 'basename_regex') :
152                                         '^(.+)\.(par2|vol\d+\+\d+|\d\d\d|part\d+|rar|zip|avi|mp4|mkv|ogm)$',
153                         ('regular expressions', 'extractable_regex') :
154                                         '^.+\.(rar|r\d\d|\d\d\d|zip)$',
155                         ('commands', 'unrar') : 'unrar x -o+ -- ',
156                         ('commands', 'unzip') : 'unzip \"%s\" -d \"%s\" ',
157                         ('commands', 'noextract') : 'mv \"%s\" \"%s\" ',
158                         ('commands', 'par2repair') : 'par2repair -- ',
159                 }
160
161                 self.__user_config = self.__read_config()
162
163
164
165
166 def main ():
167         pass
168
169 if __name__ == '__main__':
170         main ()
171