1#!/usr/bin/env python3 2# 3# Copyright 2019 - The Android Open Source Project 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16 17import collections 18import yaml 19 20# Allow yaml to dump OrderedDict 21yaml.add_representer(collections.OrderedDict, 22 lambda dumper, data: dumper.represent_dict(data), 23 Dumper=yaml.SafeDumper) 24 25 26def _str_representer(dumper, data): 27 if len(data.splitlines()) > 1: 28 data = '\n'.join(line.replace('\t', ' ').rstrip() 29 for line in data.splitlines()) 30 return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') 31 return dumper.represent_scalar('tag:yaml.org,2002:str', data) 32 33 34# Automatically convert multiline strings into block literals 35yaml.add_representer(str, _str_representer, Dumper=yaml.SafeDumper) 36 37 38_DUMP_KWARGS = dict(explicit_start=True, allow_unicode=True, indent=4) 39if yaml.__version__ >= '5.1': 40 _DUMP_KWARGS.update(sort_keys=False) 41 42 43def safe_dump(content, file): 44 """Calls yaml.safe_dump to write content to the file, with additional 45 parameters from _DUMP_KWARGS.""" 46 yaml.safe_dump(content, file, **_DUMP_KWARGS) 47