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.rstrip() for line in data.splitlines()) 29 return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') 30 return dumper.represent_scalar('tag:yaml.org,2002:str', data) 31 32 33# Automatically convert multiline strings into block literals 34yaml.add_representer(str, _str_representer, Dumper=yaml.SafeDumper) 35 36 37_DUMP_KWARGS = dict(explicit_start=True, allow_unicode=True, indent=4) 38if yaml.__version__ >= '5.1': 39 _DUMP_KWARGS.update(sort_keys=False) 40 41 42def safe_dump(content, file): 43 """Calls yaml.safe_dump to write content to the file, with additional 44 parameters from _DUMP_KWARGS.""" 45 yaml.safe_dump(content, file, **_DUMP_KWARGS) 46