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.
8 features_compiler.py --destdir gen --root /home/Work/src _permissions.json
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|.
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
),
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.
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
)
42 ('%s.cc' % schema_filename
, CCGenerator()),
43 ('%s.h' % schema_filename
, HGenerator())
46 # Generate and output the code for all features.
48 for filename
, generator
in generators
:
49 code
= generator
.Generate(feature_list
, full_path
, namespace
).Render()
51 with
open(os
.path
.join(destdir
, relpath
, filename
), 'w') as f
:
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
,