configloader.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. # Copyright (c) 2012-2013 LiuYC https://github.com/liuyichen/
  2. # Copyright 2012-2016 ksyun.com, Inc. or its affiliates. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"). You
  5. # may not use this file except in compliance with the License. A copy of
  6. # the License is located at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # or in the "license" file accompanying this file. This file is
  11. # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  12. # ANY KIND, either express or implied. See the License for the specific
  13. # language governing permissions and limitations under the License.
  14. import os
  15. import shlex
  16. import copy
  17. from six.moves import configparser
  18. import kscore.exceptions
  19. def multi_file_load_config(*filenames):
  20. """Load and combine multiple INI configs with profiles.
  21. This function will take a list of filesnames and return
  22. a single dictionary that represents the merging of the loaded
  23. config files.
  24. If any of the provided filenames does not exist, then that file
  25. is ignored. It is therefore ok to provide a list of filenames,
  26. some of which may not exist.
  27. Configuration files are **not** deep merged, only the top level
  28. keys are merged. The filenames should be passed in order of
  29. precedence. The first config file has precedence over the
  30. second config file, which has precedence over the third config file,
  31. etc. The only exception to this is that the "profiles" key is
  32. merged to combine profiles from multiple config files into a
  33. single profiles mapping. However, if a profile is defined in
  34. multiple config files, then the config file with the highest
  35. precedence is used. Profile values themselves are not merged.
  36. For example::
  37. FileA FileB FileC
  38. [foo] [foo] [bar]
  39. a=1 a=2 a=3
  40. b=2
  41. [bar] [baz] [profile a]
  42. a=2 a=3 region=e
  43. [profile a] [profile b] [profile c]
  44. region=c region=d region=f
  45. The final result of ``multi_file_load_config(FileA, FileB, FileC)``
  46. would be::
  47. {"foo": {"a": 1}, "bar": {"a": 2}, "baz": {"a": 3},
  48. "profiles": {"a": {"region": "c"}}, {"b": {"region": d"}},
  49. {"c": {"region": "f"}}}
  50. Note that the "foo" key comes from A, even though it's defined in both
  51. FileA and FileB. Because "foo" was defined in FileA first, then the values
  52. for "foo" from FileA are used and the values for "foo" from FileB are
  53. ignored. Also note where the profiles originate from. Profile "a"
  54. comes FileA, profile "b" comes from FileB, and profile "c" comes
  55. from FileC.
  56. """
  57. configs = []
  58. profiles = []
  59. for filename in filenames:
  60. try:
  61. loaded = load_config(filename)
  62. except kscore.exceptions.ConfigNotFound:
  63. continue
  64. profiles.append(loaded.pop('profiles'))
  65. configs.append(loaded)
  66. merged_config = _merge_list_of_dicts(configs)
  67. merged_profiles = _merge_list_of_dicts(profiles)
  68. merged_config['profiles'] = merged_profiles
  69. return merged_config
  70. def _merge_list_of_dicts(list_of_dicts):
  71. merged_dicts = {}
  72. for single_dict in list_of_dicts:
  73. for key, value in single_dict.items():
  74. if key not in merged_dicts:
  75. merged_dicts[key] = value
  76. return merged_dicts
  77. def load_config(config_filename):
  78. """Parse a INI config with profiles.
  79. This will parse an INI config file and map top level profiles
  80. into a top level "profile" key.
  81. If you want to parse an INI file and map all section names to
  82. top level keys, use ``raw_config_parse`` instead.
  83. """
  84. parsed = raw_config_parse(config_filename)
  85. return build_profile_map(parsed)
  86. def raw_config_parse(config_filename):
  87. """Returns the parsed INI config contents.
  88. Each section name is a top level key.
  89. :returns: A dict with keys for each profile found in the config
  90. file and the value of each key being a dict containing name
  91. value pairs found in that profile.
  92. :raises: ConfigNotFound, ConfigParseError
  93. """
  94. config = {}
  95. path = config_filename
  96. if path is not None:
  97. path = os.path.expandvars(path)
  98. path = os.path.expanduser(path)
  99. if not os.path.isfile(path):
  100. raise kscore.exceptions.ConfigNotFound(path=path)
  101. cp = configparser.RawConfigParser()
  102. try:
  103. cp.read(path)
  104. except configparser.Error:
  105. raise kscore.exceptions.ConfigParseError(path=path)
  106. else:
  107. for section in cp.sections():
  108. config[section] = {}
  109. for option in cp.options(section):
  110. config_value = cp.get(section, option)
  111. if config_value.startswith('\n'):
  112. # Then we need to parse the inner contents as
  113. # hierarchical. We support a single level
  114. # of nesting for now.
  115. try:
  116. config_value = _parse_nested(config_value)
  117. except ValueError:
  118. raise kscore.exceptions.ConfigParseError(
  119. path=path)
  120. config[section][option] = config_value
  121. return config
  122. def _parse_nested(config_value):
  123. # Given a value like this:
  124. # \n
  125. # foo = bar
  126. # bar = baz
  127. # We need to parse this into
  128. # {'foo': 'bar', 'bar': 'baz}
  129. parsed = {}
  130. for line in config_value.splitlines():
  131. line = line.strip()
  132. if not line:
  133. continue
  134. # The caller will catch ValueError
  135. # and raise an appropriate error
  136. # if this fails.
  137. key, value = line.split('=', 1)
  138. parsed[key.strip()] = value.strip()
  139. return parsed
  140. def build_profile_map(parsed_ini_config):
  141. """Convert the parsed INI config into a profile map.
  142. The config file format requires that every profile except the
  143. default to be prepended with "profile", e.g.::
  144. [profile test]
  145. aws_... = foo
  146. aws_... = bar
  147. [profile bar]
  148. aws_... = foo
  149. aws_... = bar
  150. # This is *not* a profile
  151. [preview]
  152. otherstuff = 1
  153. # Neither is this
  154. [foobar]
  155. morestuff = 2
  156. The build_profile_map will take a parsed INI config file where each top
  157. level key represents a section name, and convert into a format where all
  158. the profiles are under a single top level "profiles" key, and each key in
  159. the sub dictionary is a profile name. For example, the above config file
  160. would be converted from::
  161. {"profile test": {"aws_...": "foo", "aws...": "bar"},
  162. "profile bar": {"aws...": "foo", "aws...": "bar"},
  163. "preview": {"otherstuff": ...},
  164. "foobar": {"morestuff": ...},
  165. }
  166. into::
  167. {"profiles": {"test": {"aws_...": "foo", "aws...": "bar"},
  168. "bar": {"aws...": "foo", "aws...": "bar"},
  169. "preview": {"otherstuff": ...},
  170. "foobar": {"morestuff": ...},
  171. }
  172. If there are no profiles in the provided parsed INI contents, then
  173. an empty dict will be the value associated with the ``profiles`` key.
  174. .. note::
  175. This will not mutate the passed in parsed_ini_config. Instead it will
  176. make a deepcopy and return that value.
  177. """
  178. parsed_config = copy.deepcopy(parsed_ini_config)
  179. profiles = {}
  180. final_config = {}
  181. for key, values in parsed_config.items():
  182. if key.startswith("profile"):
  183. try:
  184. parts = shlex.split(key)
  185. except ValueError:
  186. continue
  187. if len(parts) == 2:
  188. profiles[parts[1]] = values
  189. elif key == 'default':
  190. # default section is special and is considered a profile
  191. # name but we don't require you use 'profile "default"'
  192. # as a section.
  193. profiles[key] = values
  194. else:
  195. final_config[key] = values
  196. final_config['profiles'] = profiles
  197. return final_config