blob: f773c4a6300e790d167e9dc9f940d4c63dd4c199 [file] [log] [blame]
#!/usr/bin/env python
# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
This is a very simple script to generate lib/encoding_cc.template
and lib/encoding_h.template from the C++ files in the encoding directory.
This lets us edit the .cc / .h files, which is more pleasant
(there are tests after all), and then update the templates
mechanically.
TODO(johannes): Migrate toward directly depending on encoding/encoding.{h,cc} to
obviate the need for generating a copy in lib/encoding_{h,cc}.template.
"""
def ReadBody(filename, system_includes, bodies):
inside_namespace = False
body = ['\n', '// ===== %s =====\n' % filename, '\n']
for line in open(filename):
if line == 'namespace inspector_protocol_encoding {\n':
inside_namespace = True
continue
if line == '} // namespace inspector_protocol_encoding\n':
inside_namespace = False
continue
if line.startswith('#include <'):
system_includes.append(line)
if inside_namespace:
body.append(line)
bodies.append(''.join(body))
LICENSE = """
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
"""
NAMESPACE_START = """
{% for namespace in config.protocol.namespace %}
namespace {{namespace}} {
{% endfor %}
"""
NAMESPACE_END = """
{% for namespace in config.protocol.namespace %}
} // namespace {{namespace}}
{% endfor %}
"""
def GenTemplate(with_header_guard, filename, from_cpp_files):
contents = [
'{# This template is generated by gen_cbor_templates.py. #}\n',
'// Generated by %s.\n' % filename,
LICENSE,
'\n']
contents.append('{% if config.encoding_lib.header == "" %}\n')
if with_header_guard:
contents.append('#ifndef {{"_".join(config.protocol.namespace)}}_%s_h\n' % with_header_guard)
contents.append('#define {{"_".join(config.protocol.namespace)}}_%s_h\n' % with_header_guard)
system_includes=[]
bodies=[]
for cpp_file in from_cpp_files:
ReadBody(cpp_file, system_includes, bodies)
system_includes = list(set(system_includes)) # unique
system_includes.sort()
contents.append('\n')
contents += system_includes
contents.append(NAMESPACE_START)
contents += bodies
contents.append(NAMESPACE_END)
if with_header_guard:
contents.append('#endif // !defined({{"_".join(config.protocol.namespace)}}_%s_h)' % with_header_guard)
contents.append('\n')
contents.append('{% endif %}\n')
open(filename, 'w').write(''.join(contents))
if __name__ == '__main__':
GenTemplate(with_header_guard=None, filename='lib/encoding_cpp.template',
from_cpp_files=['encoding/encoding.cc'])
GenTemplate(with_header_guard='encoding', filename='lib/encoding_h.template',
from_cpp_files=['encoding/encoding.h'])