Add ICU message format support
[chromium-blink-merge.git] / tools / json_schema_compiler / features_compiler.py
blobcb3f7ef683941d76fb01c8398c75fa92193460e9
1 #!/usr/bin/env python
2 # Copyright 2013 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
5 """Generator for C++ features from json files.
7 Usage example:
8 features_compiler.py --destdir gen --root /home/Work/src _permissions.json
9 """
11 import optparse
12 import os
14 from schema_loader import SchemaLoader
15 from features_cc_generator import CCGenerator
16 from features_h_generator import HGenerator
17 from model import CreateFeature
20 def _GenerateSchema(filename, root, destdir, namespace):
21 """Generates C++ features files from the json file |filename|.
22 """
23 # Load in the feature permissions from the JSON file.
24 schema = os.path.normpath(filename)
25 schema_loader = SchemaLoader(os.path.dirname(os.path.relpath(schema, root)),
26 os.path.dirname(schema),
27 [],
28 None)
29 schema_filename = os.path.splitext(schema)[0]
30 feature_defs = schema_loader.LoadSchema(schema)
32 # Generate a list of the features defined and a list of their models.
33 feature_list = []
34 for feature_def, feature in feature_defs.iteritems():
35 feature_list.append(CreateFeature(feature_def, feature))
37 source_file_dir, _ = os.path.split(schema)
38 relpath = os.path.relpath(os.path.normpath(source_file_dir), root)
39 full_path = os.path.join(relpath, schema)
41 generators = [
42 ('%s.cc' % schema_filename, CCGenerator()),
43 ('%s.h' % schema_filename, HGenerator())
46 # Generate and output the code for all features.
47 output_code = []
48 for filename, generator in generators:
49 code = generator.Generate(feature_list, full_path, namespace).Render()
50 if destdir:
51 with open(os.path.join(destdir, relpath, filename), 'w') as f:
52 f.write(code)
53 output_code += [filename, '', code, '']
55 return '\n'.join(output_code)
58 if __name__ == '__main__':
59 parser = optparse.OptionParser(
60 description='Generates a C++ features model from JSON schema',
61 usage='usage: %prog [option]... schema')
62 parser.add_option('-r', '--root', default='.',
63 help='logical include root directory. Path to schema files from '
64 'specified dir will be the include path.')
65 parser.add_option('-d', '--destdir',
66 help='root directory to output generated files.')
67 parser.add_option('-n', '--namespace', default='generated_features',
68 help='C++ namespace for generated files. e.g extensions::api.')
69 (opts, filenames) = parser.parse_args()
71 # Only one file is currently specified.
72 if len(filenames) != 1:
73 raise ValueError('One (and only one) file is required (for now).')
75 result = _GenerateSchema(filenames[0], opts.root, opts.destdir,
76 opts.namespace)
77 if not opts.destdir:
78 print result