Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/util/yaml.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5
6 import os
7
8 try:
9 from yaml import CSafeLoader as SafeLoader
10 except ImportError:
11 from yaml import SafeLoader
12
13
14 class UnicodeLoader(SafeLoader): # type: ignore
15 def construct_yaml_str(self, node):
16 return self.construct_scalar(node)
17
18
19 UnicodeLoader.add_constructor("tag:yaml.org,2002:str", UnicodeLoader.construct_yaml_str)
20
21
22 def load_stream(stream):
23 """
24 Parse the first YAML document in a stream
25 and produce the corresponding Python object.
26 """
27 loader = UnicodeLoader(stream)
28 try:
29 return loader.get_single_data()
30 finally:
31 loader.dispose()
32
33
34 def load_yaml(*parts):
35 """Convenience function to load a YAML file in the given path. This is
36 useful for loading kind configuration files from the kind path."""
37 filename = os.path.join(*parts)
38 with open(filename, "rb") as f:
39 return load_stream(f)