-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.py
105 lines (84 loc) · 3.19 KB
/
config.py
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
'''
Copyright 2011 by Chad Redman <chad at zhtoolkit.com>
License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html
'''
import os, pickle
import errno
class Config(dict):
configFileFullPath = None
appDir = None
dirtyDicts = False
dirtyFilters = False
dirtyExtraCols = False
def __init__(self, configFileFullPath):
# TODO platform-independent
#self.configFileFullPath = os.path.join(self.configPath, self.configFileName)
self.configFileFullPath = configFileFullPath
# self.makeWorkingDir()
self.load()
def setDefaults(self):
fields = {
#'dicts': {"cedict_ts.u8" : "cedict"},
'filters': ['Leeds internet corpus Top 300 words.u8'],
'extracolumns': ['Freq_per_Million_Leeds_internet_50k.u8'],
'currentdir': "samples",
'dictionaries': ['cedict_ts-merged-refs.u8'],
'charset': 'simplified',
}
for (k,v) in list(fields.items()):
if k not in self:
self[k] = v
# def makeWorkingDir(self):
# base = self.configPath
# for x in (base,
# os.path.join(base, "plugins"),
# os.path.join(base, "backups")):
# try:
# os.mkdir(x)
# except:
# pass
def _makedir(self, dirpath):
try:
#os.makedirs(dirpath)
#os.mkdir(dirpath, 0700)
os.mkdir(dirpath)
except OSError as e:
if e.errno != errno.EEXIST:
raise
def save(self):
# create directory if it doesn't exist
configDir = os.path.dirname(self.configFileFullPath)
try:
self._makedir(configDir)
# write to a temp file
from tempfile import mkstemp
(fd, tmpname) = mkstemp(dir=configDir)
tmpfile = os.fdopen(fd, 'w')
pickle.dump(dict(self), tmpfile)
tmpfile.close()
# the write was successful, delete config file (if exists) and rename
if os.path.isfile(self.configFileFullPath):
os.unlink(self.configFileFullPath)
os.rename(tmpname, self.configFileFullPath)
return (True, None)
except Exception as e:
#print u"Error saving preferences file %s (%s)" % (self.configFileFullPath, e)
return (False, e)
def load(self):
if os.path.isfile(self.configFileFullPath):
try:
f = open(self.configFileFullPath)
self.update(pickle.load(f))
except (IOError, EOFError):
# Corrupted format
#print u"DEBUG: config.load(): unable to read file %s: (%s)" % (self.configFileFullPath, ex)
#print u"DEBUG: Using the defaults instead"
pass
self.setDefaults()
def setDicts(self, dict_ar):
# TODO move setting of dirtyDict here instead of caller
self["dictionaries"] = dict_ar
def setFilters(self, filter_ar):
self["filters"] = filter_ar
def setExtraColumns(self, extracols_ar):
self["extracolumns"] = extracols_ar