PageRenderTime 79ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 0ms

/silversupport/util.py

https://bitbucket.org/ianb/silverlining/
Python | 84 lines | 75 code | 9 blank | 0 comment | 10 complexity | 0b7f9839dd0f308a288be57fc02e7d65 MD5 | raw file
Possible License(s): GPL-2.0
  1. import os
  2. import string
  3. from ConfigParser import ConfigParser
  4. __all__ = ['unique_name', 'asbool', 'read_config', 'fill_config_environ']
  5. def unique_name(dest_dir, name):
  6. n = 0
  7. result = name
  8. while 1:
  9. dest = os.path.join(dest_dir, result)
  10. if not os.path.exists(dest):
  11. return dest
  12. n += 1
  13. result = '%s_%03i' % (name, n)
  14. def asbool(obj, default=ValueError):
  15. if isinstance(obj, (str, unicode)):
  16. obj = obj.strip().lower()
  17. if obj in ['true', 'yes', 'on', 'y', 't', '1']:
  18. return True
  19. elif obj in ['false', 'no', 'off', 'n', 'f', '0']:
  20. return False
  21. else:
  22. if default is not ValueError:
  23. return default
  24. raise ValueError(
  25. "String is not true/false: %r" % obj)
  26. return bool(obj)
  27. def read_config(filename):
  28. if not os.path.exists(filename):
  29. raise ValueError('No file %s' % filename)
  30. parser = ConfigParser()
  31. parser.read([filename])
  32. config = {}
  33. for section in parser.sections():
  34. for option in parser.options(section):
  35. config.setdefault(section, {})[option] = parser.get(section, option)
  36. return config
  37. def fill_config_environ(config, default=''):
  38. """Fills in configuration values using string.Template
  39. substitution of environ variables
  40. If default is KeyError, then empty substitutions will raise KeyError
  41. """
  42. vars = _EnvironDict(os.environ, default)
  43. def fill(value):
  44. return string.Template(value).substitute(vars)
  45. config = config.copy()
  46. _recursive_dict_fill(config, fill)
  47. return config
  48. def _recursive_dict_fill(obj, filler):
  49. for key, value in obj.items():
  50. if isinstance(value, basestring):
  51. obj[key] = filler(value)
  52. elif isinstance(value, dict):
  53. _recursive_dict_fill(value, filler)
  54. class _EnvironDict(object):
  55. def __init__(self, source, default=''):
  56. self.source = source
  57. self.default = default
  58. def __getitem__(self, key):
  59. if key in self.source:
  60. obj = self.source[key]
  61. if obj is None:
  62. return ''
  63. return obj
  64. if self.default is KeyError:
  65. raise KeyError(key)
  66. else:
  67. return self.default