1 #!/usr/bin/env python 2 3 """ 4 Configuration management. 5 6 Copyright (C) 2017 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from compiler import parseFile 23 from os.path import isfile, join, split 24 from compiler.ast import Assign, AssName, Const, Discard, Module, Name, Stmt 25 26 config_path = [".", "/etc/imip-agent", split(__file__)[0]] 27 28 builtins = { 29 "False" : False, 30 "None" : None, 31 "True" : True, 32 } 33 34 def get_config(filename="config.txt", path=config_path): 35 36 "Obtain the configuration from 'filename', searching 'path' for the file." 37 38 for dirname in path: 39 pathname = join(dirname, filename) 40 if isfile(pathname): 41 module = parseFile(pathname) 42 break 43 else: 44 return {} 45 46 return get_config_data(module, {}) 47 48 def get_config_data(module, d): 49 50 "Interpret the parsed 'module', storing mappings in 'd'." 51 52 name = None 53 54 for node in module.getChildNodes(): 55 if isinstance(node, (Module, Stmt)): 56 get_config_data(node, d) 57 elif isinstance(node, Discard): 58 pass 59 elif isinstance(node, Assign): 60 if len(node.nodes) == 1 and isinstance(node.nodes[0], AssName): 61 name = node.nodes[0].name 62 if isinstance(node.expr, Const): 63 d[name] = node.expr.value 64 elif isinstance(node.expr, Name): 65 d[name] = d.get(node.expr.name, builtins.get(node.expr.name)) 66 67 return d 68 69 # Expose settings via a module-level name. 70 71 settings = get_config() 72 73 # vim: tabstop=4 expandtab shiftwidth=4