--- a/hwctl/rclconfig.py
+++ b/hwctl/conftree.py
@@ -1,20 +1,47 @@
#!/usr/bin/env python
+# Copyright (C) 2016 J.F.Dockes
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the
+# Free Software Foundation, Inc.,
+# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+
+from __future__ import print_function
import locale
import re
import os
import sys
import base64
+import platform
class ConfSimple:
"""A ConfSimple class reads a recoll configuration file, which is a typical
ini file (see the Recoll manual). It's a dictionary of dictionaries which
lets you retrieve named values from the top level or a subsection"""
- def __init__(self, confname, tildexp = False):
- f = open(confname, 'r')
+ def __init__(self, confname, tildexp = False, readonly = True):
+ self.submaps = {}
self.dotildexpand = tildexp
- self.submaps = {}
+ self.readonly = readonly
+ self.confname = confname
+
+ try:
+ f = open(confname, 'r')
+ except Exception as exc:
+ #print("Open Exception: %s" % exc, file=sys.stderr)
+ # File does not exist -> empty config, not an error.
+ return
self.parseinput(f)
@@ -37,45 +64,71 @@
appending = True
continue
appending = False
- #print line
+ #print(line)
if line[0] == '[':
line = line.strip('[]')
if self.dotildexpand:
submapkey = os.path.expanduser(line)
else:
submapkey = line
- #print "Submapkey:", submapkey
+ #print("Submapkey: [%s]" % submapkey)
continue
nm, sep, value = line.partition('=')
if sep == '':
continue
nm = nm.strip()
value = value.strip()
- #print "Name:", nm, "Value:", value
-
- if not self.submaps.has_key(submapkey):
+ #print("Name: [%s] Value: [%s]" % (nm, value))
+
+ if not submapkey in self.submaps:
self.submaps[submapkey] = {}
self.submaps[submapkey][nm] = value
def get(self, nm, sk = ''):
'''Returns None if not found, empty string if found empty'''
- if not self.submaps.has_key(sk):
+ if not sk in self.submaps:
return None
- if not self.submaps[sk].has_key(nm):
+ if not nm in self.submaps[sk]:
return None
return self.submaps[sk][nm]
+ def _rewrite(self):
+ if self.readonly:
+ raise Exception("ConfSimple is readonly")
+
+ tname = self.confname + "-"
+ f = open(tname, 'w')
+ # First output null subkey submap
+ if '' in self.submaps:
+ for nm,value in self.submaps[''].iteritems():
+ f.write(nm + " = " + value + "\n")
+ for sk,mp in self.submaps.iteritems():
+ if sk == '':
+ continue
+ f.write("[" + sk + "]\n")
+ for nm,value in mp.iteritems():
+ f.write(nm + " = " + value + "\n")
+ f.close()
+ os.rename(tname, self.confname)
+
+ def set(self, nm, value, sk = ''):
+ if self.readonly:
+ raise Exception("ConfSimple is readonly")
+ self.submaps[sk][nm] = value
+ self._rewrite()
+ return True
+
def getNames(self, sk = ''):
- if not self.submaps.has_key(sk):
+ if not sk in self.submaps:
return None
- return self.submaps[sk].keys()
+ return list(self.submaps[sk].keys())
class ConfTree(ConfSimple):
"""A ConfTree adds path-hierarchical interpretation of the section keys,
which should be '/'-separated values. When a value is requested for a
given path, it will also be searched in the sections corresponding to
the ancestors. E.g. get(name, '/a/b') will also look in sections '/a' and
- '/' or '' (the last 2 are equivalent"""
+ '/' or '' (the last 2 are equivalent)"""
def get(self, nm, sk = ''):
if sk == '' or sk[0] != '/':
return ConfSimple.get(self, nm, sk)
@@ -124,64 +177,24 @@
return value
return None
-class RclDynConf:
- def __init__(self, fname):
- self.data = ConfSimple(fname)
-
- def getStringList(self, sk):
- nms = self.data.getNames(sk)
- out = []
- if nms is not None:
- for nm in nms:
- out.append(base64.b64decode(self.data.get(nm, sk)))
- return out
-
-class RclConfig:
- def __init__(self, argcnf = None):
- # Find configuration directory
- if argcnf is not None:
- self.confdir = os.path.abspath(argcnf)
- elif os.environ.has_key("RECOLL_CONFDIR"):
- self.confdir = os.environ["RECOLL_CONFDIR"]
- else:
- self.confdir = os.path.expanduser("~/.recoll")
- #print "Confdir: [%s]" % self.confdir
- # Also find datadir. This is trickier because this is set by
- # "configure" in the C code. We can only do our best. Have to
- # choose a preference order. Use RECOLL_DATADIR if the order is wrong
- self.datadir = None
- if os.environ.has_key("RECOLL_DATADIR"):
- self.datadir = os.environ["RECOLL_DATADIR"]
- else:
- dirs = ("/opt/local", "/usr", "/usr/local")
- for dir in dirs:
- dd = os.path.join(dir, "share/recoll")
- if os.path.exists(dd):
- self.datadir = dd
- if self.datadir is None:
- self.datadir = "/usr/share/recoll"
- #print "Datadir: [%s]" % self.datadir
- self.cdirs = [self.confdir,]
- self.cdirs.append(os.path.join(self.datadir, "examples"))
- #print self.cdirs
- self.config = ConfStack("recoll.conf", self.cdirs, "tree")
- self.keydir = ''
-
- def getConfDir(self):
- return self.confdir
-
- def setKeyDir(self, dir):
- self.keydir = dir
-
- def getConfParam(self, nm):
- return self.config.get(nm, self.keydir)
-
-class RclExtraDbs:
- def __init__(self, config):
- self.config = config
-
- def getActDbs(self):
- dyncfile = os.path.join(self.config.getConfDir(), "history")
- dync = RclDynConf(dyncfile)
- return dync.getStringList("actExtDbs")
-
+if __name__ == '__main__':
+ def Usage():
+ print("Usage: conftree.py <filename> <paramname> [<section>]",
+ file=sys.stderr)
+ sys.exit(1)
+ section = ''
+ if len(sys.argv) >= 3:
+ fname = sys.argv[1]
+ pname = sys.argv[2]
+ if len(sys.argv) == 4:
+ section = sys.argv[3]
+ elif len(sys.argv) != 3:
+ Usage()
+ else:
+ Usage()
+
+ conf = ConfSimple(fname)
+ if section:
+ print("[%s] %s -> %s" % (section, pname, conf.get(pname)))
+ else:
+ print("%s -> %s" % (pname, conf.get(pname)))