Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(618)

Side by Side Diff: components/policy/tools/generate_policy_source.py

Issue 2726103004: Generate code for encoding cloud policy protobufs (Closed)
Patch Set: Incorporated emaxx's comments. Created 3 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « no previous file | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 #!/usr/bin/env python 1 #!/usr/bin/env python
2 # Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be 3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file. 4 # found in the LICENSE file.
5 5
6 '''python %prog [options] platform chromium_os_flag template 6 '''python %prog [options] platform chromium_os_flag template
7 7
8 platform specifies which platform source is being generated for 8 platform specifies which platform source is being generated for
9 and can be one of (win, mac, linux) 9 and can be one of (win, mac, linux)
10 chromium_os_flag should be 1 if this is a Chromium OS build 10 chromium_os_flag should be 1 if this is a Chromium OS build
(...skipping 189 matching lines...) Expand 10 before | Expand all | Expand 10 after
200 metavar='FILE') 200 metavar='FILE')
201 parser.add_option('--ard', '--app-restrictions-definition', 201 parser.add_option('--ard', '--app-restrictions-definition',
202 dest='app_restrictions_path', 202 dest='app_restrictions_path',
203 help='generate an XML file as specified by ' 203 help='generate an XML file as specified by '
204 'Android\'s App Restriction Schema', 204 'Android\'s App Restriction Schema',
205 metavar='FILE') 205 metavar='FILE')
206 parser.add_option('--rth', '--risk-tag-header', 206 parser.add_option('--rth', '--risk-tag-header',
207 dest='risk_header_path', 207 dest='risk_header_path',
208 help='generate header file for policy risk tags', 208 help='generate header file for policy risk tags',
209 metavar='FILE') 209 metavar='FILE')
210 parser.add_option('--crospch', '--cros-policy-constants-header',
211 dest='cros_constants_header_path',
212 help='generate header file of policy constants for use in '
213 'Chrome OS',
214 metavar='FILE')
215 parser.add_option('--crospcc', '--cros-policy-constants-source',
216 dest='cros_constants_source_path',
217 help='generate source file of policy constants for use in '
218 'Chrome OS',
219 metavar='FILE')
210 (opts, args) = parser.parse_args() 220 (opts, args) = parser.parse_args()
211 221
212 if len(args) != 4: 222 if len(args) != 4:
213 print('Please specify path to src/chrome/VERSION, platform, ' 223 print('Please specify path to src/chrome/VERSION, platform, '
214 'chromium_os flag and input file as positional parameters.') 224 'chromium_os flag and input file as positional parameters.')
215 parser.print_help() 225 parser.print_help()
216 return 2 226 return 2
217 227
218 version_path = args[0] 228 version_path = args[0]
219 os = args[1] 229 os = args[1]
220 is_chromium_os = args[2] == '1' 230 is_chromium_os = args[2] == '1'
221 template_file_name = args[3] 231 template_file_name = args[3]
222 232
223 major_version = ParseVersionFile(version_path) 233 major_version = ParseVersionFile(version_path)
224 template_file_contents = _LoadJSONFile(template_file_name) 234 template_file_contents = _LoadJSONFile(template_file_name)
225 riskTags = RiskTags(template_file_contents) 235 risk_tags = RiskTags(template_file_contents)
226 policy_details = [ PolicyDetails(policy, major_version, os, is_chromium_os, 236 policy_details = [ PolicyDetails(policy, major_version, os, is_chromium_os,
227 riskTags.GetValidTags()) 237 risk_tags.GetValidTags())
228 for policy in _Flatten(template_file_contents) ] 238 for policy in _Flatten(template_file_contents) ]
229 riskTags.ComputeMaxTags(policy_details) 239 risk_tags.ComputeMaxTags(policy_details)
230 sorted_policy_details = sorted(policy_details, key=lambda policy: policy.name) 240 sorted_policy_details = sorted(policy_details, key=lambda policy: policy.name)
231 241
232 def GenerateFile(path, writer, sorted=False, xml=False): 242 def GenerateFile(path, writer, sorted=False, xml=False):
233 if path: 243 if path:
234 with open(path, 'w') as f: 244 with open(path, 'w') as f:
235 _OutputGeneratedWarningHeader(f, template_file_name, xml) 245 _OutputGeneratedWarningHeader(f, template_file_name, xml)
236 writer(sorted and sorted_policy_details or policy_details, 246 writer(sorted and sorted_policy_details or policy_details,
237 os, f, riskTags) 247 os, f, risk_tags)
238 248
239 if opts.header_path: 249 if opts.header_path:
240 GenerateFile(opts.header_path, _WritePolicyConstantHeader, sorted=True) 250 GenerateFile(opts.header_path, _WritePolicyConstantHeader, sorted=True)
241 if opts.source_path: 251 if opts.source_path:
242 GenerateFile(opts.source_path, _WritePolicyConstantSource, sorted=True) 252 GenerateFile(opts.source_path, _WritePolicyConstantSource, sorted=True)
243 if opts.risk_header_path: 253 if opts.risk_header_path:
244 GenerateFile(opts.risk_header_path, _WritePolicyRiskTagHeader) 254 GenerateFile(opts.risk_header_path, _WritePolicyRiskTagHeader)
245 if opts.cloud_policy_proto_path: 255 if opts.cloud_policy_proto_path:
246 GenerateFile(opts.cloud_policy_proto_path, _WriteCloudPolicyProtobuf) 256 GenerateFile(opts.cloud_policy_proto_path, _WriteCloudPolicyProtobuf)
247 if opts.cloud_policy_full_runtime_proto_path: 257 if opts.cloud_policy_full_runtime_proto_path:
248 GenerateFile(opts.cloud_policy_full_runtime_proto_path, 258 GenerateFile(opts.cloud_policy_full_runtime_proto_path,
249 _WriteCloudPolicyFullRuntimeProtobuf) 259 _WriteCloudPolicyFullRuntimeProtobuf)
250 if opts.chrome_settings_proto_path: 260 if opts.chrome_settings_proto_path:
251 GenerateFile(opts.chrome_settings_proto_path, _WriteChromeSettingsProtobuf) 261 GenerateFile(opts.chrome_settings_proto_path, _WriteChromeSettingsProtobuf)
252 if opts.chrome_settings_full_runtime_proto_path: 262 if opts.chrome_settings_full_runtime_proto_path:
253 GenerateFile(opts.chrome_settings_full_runtime_proto_path, 263 GenerateFile(opts.chrome_settings_full_runtime_proto_path,
254 _WriteChromeSettingsFullRuntimeProtobuf) 264 _WriteChromeSettingsFullRuntimeProtobuf)
255 if opts.cloud_policy_decoder_path: 265 if opts.cloud_policy_decoder_path:
256 GenerateFile(opts.cloud_policy_decoder_path, _WriteCloudPolicyDecoder) 266 GenerateFile(opts.cloud_policy_decoder_path, _WriteCloudPolicyDecoder)
257 267
258 if os == 'android' and opts.app_restrictions_path: 268 if os == 'android' and opts.app_restrictions_path:
259 GenerateFile(opts.app_restrictions_path, _WriteAppRestrictions, xml=True) 269 GenerateFile(opts.app_restrictions_path, _WriteAppRestrictions, xml=True)
260 270
271 # Generated code for Chrome OS (unused in Chromium).
272 if opts.cros_constants_header_path:
273 GenerateFile(opts.cros_constants_header_path,
274 _WriteChromeOSPolicyConstantsHeader, sorted=True)
275 if opts.cros_constants_source_path:
276 GenerateFile(opts.cros_constants_source_path,
277 _WriteChromeOSPolicyConstantsSource, sorted=True)
278
261 return 0 279 return 0
262 280
263 281
264 #------------------ shared helpers ---------------------------------# 282 #------------------ shared helpers ---------------------------------#
265 283
266 def _OutputGeneratedWarningHeader(f, template_file_path, xml_style): 284 def _OutputGeneratedWarningHeader(f, template_file_path, xml_style):
267 left_margin = '//' 285 left_margin = '//'
268 if xml_style: 286 if xml_style:
269 left_margin = ' ' 287 left_margin = ' '
270 f.write('<?xml version="1.0" encoding="utf-8"?>\n' 288 f.write('<?xml version="1.0" encoding="utf-8"?>\n'
(...skipping 39 matching lines...) Expand 10 before | Expand all | Expand 10 after
310 328
311 329
312 def _LoadJSONFile(json_file): 330 def _LoadJSONFile(json_file):
313 with open(json_file, 'r') as f: 331 with open(json_file, 'r') as f:
314 text = f.read() 332 text = f.read()
315 return eval(text) 333 return eval(text)
316 334
317 335
318 #------------------ policy constants header ------------------------# 336 #------------------ policy constants header ------------------------#
319 337
320 def _WritePolicyConstantHeader(policies, os, f, riskTags): 338 def _WritePolicyConstantHeader(policies, os, f, risk_tags):
321 f.write('#ifndef CHROME_COMMON_POLICY_CONSTANTS_H_\n' 339 f.write('#ifndef CHROME_COMMON_POLICY_CONSTANTS_H_\n'
322 '#define CHROME_COMMON_POLICY_CONSTANTS_H_\n' 340 '#define CHROME_COMMON_POLICY_CONSTANTS_H_\n'
323 '\n' 341 '\n'
324 '#include <string>\n' 342 '#include <string>\n'
325 '\n' 343 '\n'
326 '#include "base/values.h"\n' 344 '#include "base/values.h"\n'
327 '#include "components/policy/core/common/policy_details.h"\n' 345 '#include "components/policy/core/common/policy_details.h"\n'
328 '#include "components/policy/core/common/policy_map.h"\n' 346 '#include "components/policy/core/common/policy_map.h"\n'
329 '\n' 347 '\n'
330 'namespace policy {\n' 348 'namespace policy {\n'
(...skipping 368 matching lines...) Expand 10 before | Expand all | Expand 10 after
699 setup = ['auto default_value = base::MakeUnique<base::ListValue>();'] 717 setup = ['auto default_value = base::MakeUnique<base::ListValue>();']
700 for entry in value: 718 for entry in value:
701 decl, fetch = _GenerateDefaultValue(entry) 719 decl, fetch = _GenerateDefaultValue(entry)
702 # Nested lists are not supported. 720 # Nested lists are not supported.
703 if decl: 721 if decl:
704 return [], None 722 return [], None
705 setup.append('default_value->Append(%s);' % fetch) 723 setup.append('default_value->Append(%s);' % fetch)
706 return setup, 'std::move(default_value)' 724 return setup, 'std::move(default_value)'
707 return [], None 725 return [], None
708 726
709 def _WritePolicyConstantSource(policies, os, f, riskTags): 727 def _WritePolicyConstantSource(policies, os, f, risk_tags):
710 f.write('#include "components/policy/policy_constants.h"\n' 728 f.write('#include "components/policy/policy_constants.h"\n'
711 '\n' 729 '\n'
712 '#include <algorithm>\n' 730 '#include <algorithm>\n'
713 '#include <climits>\n' 731 '#include <climits>\n'
714 '\n' 732 '\n'
715 '#include "base/logging.h"\n' 733 '#include "base/logging.h"\n'
716 '#include "base/memory/ptr_util.h"\n' 734 '#include "base/memory/ptr_util.h"\n'
717 '#include "components/policy/core/common/policy_types.h"\n' 735 '#include "components/policy/core/common/policy_types.h"\n'
718 '#include "components/policy/core/common/schema_internal.h"\n' 736 '#include "components/policy/core/common/schema_internal.h"\n'
719 '#include "components/policy/risk_tag.h"\n' 737 '#include "components/policy/risk_tag.h"\n'
(...skipping 20 matching lines...) Expand all
740 '// is_deprecated is_device_policy id max_external_data_size\n') 758 '// is_deprecated is_device_policy id max_external_data_size\n')
741 for policy in policies: 759 for policy in policies:
742 if policy.is_supported: 760 if policy.is_supported:
743 f.write(' // %s\n' % policy.name) 761 f.write(' // %s\n' % policy.name)
744 f.write(' { %-14s %-16s %3s, %24s,\n' 762 f.write(' { %-14s %-16s %3s, %24s,\n'
745 ' %s },\n' % ( 763 ' %s },\n' % (
746 'true,' if policy.is_deprecated else 'false,', 764 'true,' if policy.is_deprecated else 'false,',
747 'true,' if policy.is_device_only else 'false,', 765 'true,' if policy.is_device_only else 'false,',
748 policy.id, 766 policy.id,
749 policy.max_size, 767 policy.max_size,
750 riskTags.ToInitString(policy.tags))) 768 risk_tags.ToInitString(policy.tags)))
751 f.write('};\n\n') 769 f.write('};\n\n')
752 770
753 schema_generator = SchemaNodesGenerator(shared_strings) 771 schema_generator = SchemaNodesGenerator(shared_strings)
754 schema_generator.GenerateAndCollectID(chrome_schema, 'root node') 772 schema_generator.GenerateAndCollectID(chrome_schema, 'root node')
755 schema_generator.ResolveReferences() 773 schema_generator.ResolveReferences()
756 schema_generator.Write(f) 774 schema_generator.Write(f)
757 775
758 f.write('\n' 776 f.write('\n'
759 'namespace {\n') 777 'namespace {\n')
760 778
(...skipping 83 matching lines...) Expand 10 before | Expand all | Expand 10 after
844 for policy in policies: 862 for policy in policies:
845 # TODO(joaodasilva): Include only supported policies in 863 # TODO(joaodasilva): Include only supported policies in
846 # configuration_policy_handler.cc and configuration_policy_handler_list.cc 864 # configuration_policy_handler.cc and configuration_policy_handler_list.cc
847 # so that these names can be conditional on 'policy.is_supported'. 865 # so that these names can be conditional on 'policy.is_supported'.
848 # http://crbug.com/223616 866 # http://crbug.com/223616
849 f.write('const char k{name}[] = "{name}";\n'.format(name=policy.name)) 867 f.write('const char k{name}[] = "{name}";\n'.format(name=policy.name))
850 f.write('\n} // namespace key\n\n' 868 f.write('\n} // namespace key\n\n'
851 '} // namespace policy\n') 869 '} // namespace policy\n')
852 870
853 871
854 #------------------ policy risk tag header ------------------------# 872 #------------------ policy risk tag header -------------------------#
855 873
856 class RiskTags(object): 874 class RiskTags(object):
857 '''Generates files and strings to translate the parsed risk tags.''' 875 '''Generates files and strings to translate the parsed risk tags.'''
858 # TODO(fhorschig|tnagel): Add, Check & Generate translation descriptions. 876 # TODO(fhorschig|tnagel): Add, Check & Generate translation descriptions.
859 877
860 def __init__(self, template_file_contents): 878 def __init__(self, template_file_contents):
861 self.max_tags = None 879 self.max_tags = None
862 self.enum_for_tag = OrderedDict() # Ordered by severity as stated in JSON. 880 self.enum_for_tag = OrderedDict() # Ordered by severity as stated in JSON.
863 self._ReadRiskTagMetaData(template_file_contents) 881 self._ReadRiskTagMetaData(template_file_contents)
864 882
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
901 if tag.get('name', None) == None: 919 if tag.get('name', None) == None:
902 raise RuntimeError('Tag in \'risk_tag_definitions\' without ' 920 raise RuntimeError('Tag in \'risk_tag_definitions\' without '
903 'description found!') 921 'description found!')
904 if tag.get('description', None) == None: 922 if tag.get('description', None) == None:
905 raise RuntimeError('Tag ' + tag['name'] + ' has no description!') 923 raise RuntimeError('Tag ' + tag['name'] + ' has no description!')
906 if tag.get('user-description', None) == None: 924 if tag.get('user-description', None) == None:
907 raise RuntimeError('Tag ' + tag['name'] + ' has no user-description!') 925 raise RuntimeError('Tag ' + tag['name'] + ' has no user-description!')
908 self.enum_for_tag[tag['name']] = "RISK_TAG_" + \ 926 self.enum_for_tag[tag['name']] = "RISK_TAG_" + \
909 tag['name'].replace("-","_").upper() 927 tag['name'].replace("-","_").upper()
910 928
911 def _WritePolicyRiskTagHeader(policies, os, f, riskTags): 929 def _WritePolicyRiskTagHeader(policies, os, f, risk_tags):
912 f.write('#ifndef CHROME_COMMON_POLICY_RISK_TAG_H_\n' 930 f.write('#ifndef CHROME_COMMON_POLICY_RISK_TAG_H_\n'
913 '#define CHROME_COMMON_POLICY_RISK_TAG_H_\n' 931 '#define CHROME_COMMON_POLICY_RISK_TAG_H_\n'
914 '\n' 932 '\n'
915 '#include <stddef.h>\n' 933 '#include <stddef.h>\n'
916 '\n' 934 '\n'
917 'namespace policy {\n' 935 'namespace policy {\n'
918 '\n' + \ 936 '\n' + \
919 '// The tag of a policy indicates which impact a policy can have on\n' 937 '// The tag of a policy indicates which impact a policy can have on\n'
920 '// a user\'s privacy and/or security. Ordered descending by \n' 938 '// a user\'s privacy and/or security. Ordered descending by \n'
921 '// impact.\n' 939 '// impact.\n'
922 '// The explanation of the single tags is stated in\n' 940 '// The explanation of the single tags is stated in\n'
923 '// policy_templates.json within the \'risk_tag_definitions\' tag.' 941 '// policy_templates.json within the \'risk_tag_definitions\' tag.'
924 '\n' + riskTags.GenerateEnum() + '\n' 942 '\n' + risk_tags.GenerateEnum() + '\n'
925 '// This constant describes how many risk tags were used by the\n' 943 '// This constant describes how many risk tags were used by the\n'
926 '// policy which uses the most risk tags. \n' 944 '// policy which uses the most risk tags. \n'
927 'const size_t kMaxRiskTagCount = ' + \ 945 'const size_t kMaxRiskTagCount = ' + \
928 riskTags.GetMaxTags() + ';\n' 946 risk_tags.GetMaxTags() + ';\n'
929 '\n' 947 '\n'
930 '} // namespace policy\n' 948 '} // namespace policy\n'
931 '\n' 949 '\n'
932 '#endif // CHROME_COMMON_POLICY_RISK_TAG_H_' 950 '#endif // CHROME_COMMON_POLICY_RISK_TAG_H_'
933 '\n') 951 '\n')
934 952
935 #------------------ policy protobufs --------------------------------# 953 #------------------ policy protobufs -------------------------------#
936 954
937 CHROME_SETTINGS_PROTO_HEAD = ''' 955 CHROME_SETTINGS_PROTO_HEAD = '''
938 syntax = "proto2"; 956 syntax = "proto2";
939 957
940 option optimize_for = LITE_RUNTIME; 958 option optimize_for = LITE_RUNTIME;
941 959
942 package enterprise_management; 960 package enterprise_management;
943 961
944 // For StringList and PolicyOptions. 962 // For StringList and PolicyOptions.
945 import "cloud_policy.proto"; 963 import "cloud_policy.proto";
(...skipping 66 matching lines...) Expand 10 before | Expand all | Expand 10 after
1012 _OutputComment(f, '\nNote: this policy must have a RECOMMENDED ' +\ 1030 _OutputComment(f, '\nNote: this policy must have a RECOMMENDED ' +\
1013 'PolicyMode set in PolicyOptions.') 1031 'PolicyMode set in PolicyOptions.')
1014 f.write('message %sProto {\n' % policy.name) 1032 f.write('message %sProto {\n' % policy.name)
1015 f.write(' optional PolicyOptions policy_options = 1;\n') 1033 f.write(' optional PolicyOptions policy_options = 1;\n')
1016 f.write(' optional %s %s = 2;\n' % (policy.protobuf_type, policy.name)) 1034 f.write(' optional %s %s = 2;\n' % (policy.protobuf_type, policy.name))
1017 f.write('}\n\n') 1035 f.write('}\n\n')
1018 fields += [ ' optional %sProto %s = %s;\n' % 1036 fields += [ ' optional %sProto %s = %s;\n' %
1019 (policy.name, policy.name, policy.id + RESERVED_IDS) ] 1037 (policy.name, policy.name, policy.id + RESERVED_IDS) ]
1020 1038
1021 1039
1022 def _WriteChromeSettingsProtobuf(policies, os, f, riskTags): 1040 def _WriteChromeSettingsProtobuf(policies, os, f, risk_tags):
1023 f.write(CHROME_SETTINGS_PROTO_HEAD) 1041 f.write(CHROME_SETTINGS_PROTO_HEAD)
1024 fields = [] 1042 fields = []
1025 f.write('// PBs for individual settings.\n\n') 1043 f.write('// PBs for individual settings.\n\n')
1026 for policy in policies: 1044 for policy in policies:
1027 # Note: This protobuf also gets the unsupported policies, since it's an 1045 # Note: This protobuf also gets the unsupported policies, since it's an
1028 # exhaustive list of all the supported user policies on any platform. 1046 # exhaustive list of all the supported user policies on any platform.
1029 if not policy.is_device_only: 1047 if not policy.is_device_only:
1030 _WritePolicyProto(f, policy, fields) 1048 _WritePolicyProto(f, policy, fields)
1031 1049
1032 f.write('// --------------------------------------------------\n' 1050 f.write('// --------------------------------------------------\n'
1033 '// Big wrapper PB containing the above groups.\n\n' 1051 '// Big wrapper PB containing the above groups.\n\n'
1034 'message ChromeSettingsProto {\n') 1052 'message ChromeSettingsProto {\n')
1035 f.write(''.join(fields)) 1053 f.write(''.join(fields))
1036 f.write('}\n\n') 1054 f.write('}\n\n')
1037 1055
1038 1056
1039 def _WriteChromeSettingsFullRuntimeProtobuf(policies, os, f, riskTags): 1057 def _WriteChromeSettingsFullRuntimeProtobuf(policies, os, f, risk_tags):
1040 # For full runtime, disable LITE_RUNTIME switch and import full runtime 1058 # For full runtime, disable LITE_RUNTIME switch and import full runtime
1041 # version of cloud_policy.proto. 1059 # version of cloud_policy.proto.
1042 f.write(CHROME_SETTINGS_PROTO_HEAD.replace( 1060 f.write(CHROME_SETTINGS_PROTO_HEAD.replace(
1043 "option optimize_for = LITE_RUNTIME;", 1061 "option optimize_for = LITE_RUNTIME;",
1044 "//option optimize_for = LITE_RUNTIME;").replace( 1062 "//option optimize_for = LITE_RUNTIME;").replace(
1045 "import \"cloud_policy.proto\";", 1063 "import \"cloud_policy.proto\";",
1046 "import \"cloud_policy_full_runtime.proto\";" 1064 "import \"cloud_policy_full_runtime.proto\";"
1047 )) 1065 ))
1048 fields = [] 1066 fields = []
1049 f.write('// PBs for individual settings.\n\n') 1067 f.write('// PBs for individual settings.\n\n')
1050 for policy in policies: 1068 for policy in policies:
1051 # Note: This protobuf also gets the unsupported policies, since it's an 1069 # Note: This protobuf also gets the unsupported policies, since it's an
1052 # exhaustive list of all the supported user policies on any platform. 1070 # exhaustive list of all the supported user policies on any platform.
1053 if not policy.is_device_only: 1071 if not policy.is_device_only:
1054 _WritePolicyProto(f, policy, fields) 1072 _WritePolicyProto(f, policy, fields)
1055 1073
1056 f.write('// --------------------------------------------------\n' 1074 f.write('// --------------------------------------------------\n'
1057 '// Big wrapper PB containing the above groups.\n\n' 1075 '// Big wrapper PB containing the above groups.\n\n'
1058 'message ChromeSettingsProto {\n') 1076 'message ChromeSettingsProto {\n')
1059 f.write(''.join(fields)) 1077 f.write(''.join(fields))
1060 f.write('}\n\n') 1078 f.write('}\n\n')
1061 1079
1062 1080
1063 def _WriteCloudPolicyProtobuf(policies, os, f, riskTags): 1081 def _WriteCloudPolicyProtobuf(policies, os, f, risk_tags):
1064 f.write(CLOUD_POLICY_PROTO_HEAD) 1082 f.write(CLOUD_POLICY_PROTO_HEAD)
1065 f.write('message CloudPolicySettings {\n') 1083 f.write('message CloudPolicySettings {\n')
1066 for policy in policies: 1084 for policy in policies:
1067 if policy.is_supported and not policy.is_device_only: 1085 if policy.is_supported and not policy.is_device_only:
1068 f.write(' optional %sPolicyProto %s = %s;\n' % 1086 f.write(' optional %sPolicyProto %s = %s;\n' %
1069 (policy.policy_protobuf_type, policy.name, 1087 (policy.policy_protobuf_type, policy.name,
1070 policy.id + RESERVED_IDS)) 1088 policy.id + RESERVED_IDS))
1071 f.write('}\n\n') 1089 f.write('}\n\n')
1072 1090
1073 1091
1074 def _WriteCloudPolicyFullRuntimeProtobuf(policies, os, f, riskTags): 1092 def _WriteCloudPolicyFullRuntimeProtobuf(policies, os, f, risk_tags):
1075 # For full runtime, disable LITE_RUNTIME switch 1093 # For full runtime, disable LITE_RUNTIME switch
1076 f.write(CLOUD_POLICY_PROTO_HEAD.replace( 1094 f.write(CLOUD_POLICY_PROTO_HEAD.replace(
1077 "option optimize_for = LITE_RUNTIME;", 1095 "option optimize_for = LITE_RUNTIME;",
1078 "//option optimize_for = LITE_RUNTIME;")) 1096 "//option optimize_for = LITE_RUNTIME;"))
1079 f.write('message CloudPolicySettings {\n') 1097 f.write('message CloudPolicySettings {\n')
1080 for policy in policies: 1098 for policy in policies:
1081 if policy.is_supported and not policy.is_device_only: 1099 if policy.is_supported and not policy.is_device_only:
1082 f.write(' optional %sPolicyProto %s = %s;\n' % 1100 f.write(' optional %sPolicyProto %s = %s;\n' %
1083 (policy.policy_protobuf_type, policy.name, 1101 (policy.policy_protobuf_type, policy.name,
1084 policy.id + RESERVED_IDS)) 1102 policy.id + RESERVED_IDS))
1085 f.write('}\n\n') 1103 f.write('}\n\n')
1086 1104
1087 1105
1088 #------------------ protobuf decoder -------------------------------# 1106 #------------------ protobuf decoder -------------------------------#
1089 1107
1090 CPP_HEAD = ''' 1108 CLOUD_POLICY_DECODER_CPP_HEAD = '''
1091 #include <limits> 1109 #include <limits>
1092 #include <memory> 1110 #include <memory>
1093 #include <utility> 1111 #include <utility>
1094 #include <string> 1112 #include <string>
1095 1113
1096 #include "base/callback.h" 1114 #include "base/callback.h"
1097 #include "base/json/json_reader.h" 1115 #include "base/json/json_reader.h"
1098 #include "base/logging.h" 1116 #include "base/logging.h"
1099 #include "base/memory/ptr_util.h" 1117 #include "base/memory/ptr_util.h"
1100 #include "base/memory/weak_ptr.h" 1118 #include "base/memory/weak_ptr.h"
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after
1144 // convert and check the concrete type. 1162 // convert and check the concrete type.
1145 return root; 1163 return root;
1146 } 1164 }
1147 1165
1148 void DecodePolicy(const em::CloudPolicySettings& policy, 1166 void DecodePolicy(const em::CloudPolicySettings& policy,
1149 base::WeakPtr<CloudExternalDataManager> external_data_manager, 1167 base::WeakPtr<CloudExternalDataManager> external_data_manager,
1150 PolicyMap* map) { 1168 PolicyMap* map) {
1151 ''' 1169 '''
1152 1170
1153 1171
1154 CPP_FOOT = '''} 1172 CLOUD_POLICY_DECODER_CPP_FOOT = '''}
1155 1173
1156 } // namespace policy 1174 } // namespace policy
1157 ''' 1175 '''
1158 1176
1159 1177
1160 def _CreateValue(type, arg): 1178 def _CreateValue(type, arg):
1161 if type == 'Type::BOOLEAN': 1179 if type == 'Type::BOOLEAN':
1162 return 'new base::Value(%s)' % arg 1180 return 'new base::Value(%s)' % arg
1163 elif type == 'Type::INTEGER': 1181 elif type == 'Type::INTEGER':
1164 return 'DecodeIntegerValue(%s)' % arg 1182 return 'DecodeIntegerValue(%s)' % arg
1165 elif type == 'Type::STRING': 1183 elif type == 'Type::STRING':
1166 return 'new base::Value(%s)' % arg 1184 return 'new base::Value(%s)' % arg
1167 elif type == 'Type::LIST': 1185 elif type == 'Type::LIST':
1168 return 'DecodeStringList(%s)' % arg 1186 return 'DecodeStringList(%s)' % arg
1169 elif type == 'Type::DICTIONARY' or type == 'TYPE_EXTERNAL': 1187 elif type == 'Type::DICTIONARY' or type == 'TYPE_EXTERNAL':
1170 return 'DecodeJson(%s)' % arg 1188 return 'DecodeJson(%s)' % arg
1171 else: 1189 else:
1172 raise NotImplementedError('Unknown type %s' % type) 1190 raise NotImplementedError('Unknown type %s' % type)
1173 1191
1174 1192
1175 def _CreateExternalDataFetcher(type, name): 1193 def _CreateExternalDataFetcher(type, name):
1176 if type == 'TYPE_EXTERNAL': 1194 if type == 'TYPE_EXTERNAL':
1177 return 'new ExternalDataFetcher(external_data_manager, key::k%s)' % name 1195 return 'new ExternalDataFetcher(external_data_manager, key::k%s)' % name
1178 return 'nullptr' 1196 return 'nullptr'
1179 1197
1180 1198
1181 def _WritePolicyCode(f, policy): 1199 def _WriteCloudPolicyDecoderCode(f, policy):
1182 membername = policy.name.lower() 1200 membername = policy.name.lower()
1183 proto_type = '%sPolicyProto' % policy.policy_protobuf_type 1201 proto_type = '%sPolicyProto' % policy.policy_protobuf_type
1184 f.write(' if (policy.has_%s()) {\n' % membername) 1202 f.write(' if (policy.has_%s()) {\n' % membername)
1185 f.write(' const em::%s& policy_proto = policy.%s();\n' % 1203 f.write(' const em::%s& policy_proto = policy.%s();\n' %
1186 (proto_type, membername)) 1204 (proto_type, membername))
1187 f.write(' if (policy_proto.has_value()) {\n') 1205 f.write(' if (policy_proto.has_value()) {\n')
1188 f.write(' PolicyLevel level = POLICY_LEVEL_MANDATORY;\n' 1206 f.write(' PolicyLevel level = POLICY_LEVEL_MANDATORY;\n'
1189 ' bool do_set = true;\n' 1207 ' bool do_set = true;\n'
1190 ' if (policy_proto.has_policy_options()) {\n' 1208 ' if (policy_proto.has_policy_options()) {\n'
1191 ' do_set = false;\n' 1209 ' do_set = false;\n'
(...skipping 24 matching lines...) Expand all
1216 ' POLICY_SCOPE_USER, \n' 1234 ' POLICY_SCOPE_USER, \n'
1217 ' POLICY_SOURCE_CLOUD, \n' 1235 ' POLICY_SOURCE_CLOUD, \n'
1218 ' std::move(value), \n' 1236 ' std::move(value), \n'
1219 ' std::move(external_data_fetcher));\n' 1237 ' std::move(external_data_fetcher));\n'
1220 ' }\n' 1238 ' }\n'
1221 ' }\n' 1239 ' }\n'
1222 ' }\n' 1240 ' }\n'
1223 ' }\n') 1241 ' }\n')
1224 1242
1225 1243
1226 def _WriteCloudPolicyDecoder(policies, os, f, riskTags): 1244 def _WriteCloudPolicyDecoder(policies, os, f, risk_tags):
1227 f.write(CPP_HEAD) 1245 f.write(CLOUD_POLICY_DECODER_CPP_HEAD)
1228 for policy in policies: 1246 for policy in policies:
1229 if policy.is_supported and not policy.is_device_only: 1247 if policy.is_supported and not policy.is_device_only:
1230 _WritePolicyCode(f, policy) 1248 _WriteCloudPolicyDecoderCode(f, policy)
1231 f.write(CPP_FOOT) 1249 f.write(CLOUD_POLICY_DECODER_CPP_FOOT)
1232 1250
1233 1251
1234 def _WriteAppRestrictions(policies, os, f, riskTags): 1252 #------------------ Chrome OS policy constants header --------------#
1253
1254 # Returns a list of supported user policies by filtering |policies|.
1255 def _GetSupportedUserPolicies(policies):
1256 return filter(lambda policy: policy.is_supported and
1257 not policy.is_device_only, policies)
1258
1259
1260 # Returns the set of all policy.policy_protobuf_type strings from |policies|.
1261 def _GetProtobufTypes(policies):
1262 return set(policy.policy_protobuf_type for policy in policies)
1263
1264
1265 # Writes the definition of an array that contains the pointers to the mutable
1266 # proto field for each policy in |policies| of the given |protobuf_type|.
1267 def _WriteChromeOSPolicyAccessHeader(f, protobuf_type):
1268 f.write('// Access to the mutable protobuf function of all supported '
1269 '%s user\n// policies.\n' % protobuf_type.lower())
1270 f.write('struct %sPolicyAccess {\n'
1271 ' const char* policy_key;\n'
1272 ' enterprise_management::%sPolicyProto*\n'
1273 ' (enterprise_management::CloudPolicySettings::'
1274 '*mutable_proto_ptr)();\n'
1275 '};\n' % (protobuf_type, protobuf_type))
1276 f.write('extern const %sPolicyAccess k%sPolicyAccess[];\n\n'
1277 % (protobuf_type, protobuf_type))
1278
1279
1280 # Writes policy_constants.h for use in Chrome OS.
1281 def _WriteChromeOSPolicyConstantsHeader(policies, os, f, risk_tags):
1282 f.write('#ifndef __BINDINGS_POLICY_CONSTANTS_H_\n'
1283 '#define __BINDINGS_POLICY_CONSTANTS_H_\n\n')
1284
1285 # Forward declarations.
1286 supported_user_policies = _GetSupportedUserPolicies(policies)
1287 protobuf_types = _GetProtobufTypes(supported_user_policies)
1288 f.write('namespace enterprise_management {\n'
1289 'class CloudPolicySettings;\n')
1290 for protobuf_type in protobuf_types:
1291 f.write('class %sPolicyProto;\n' % protobuf_type)
1292 f.write('} // namespace enterprise_management\n\n')
1293
1294 f.write('namespace policy {\n\n')
1295
1296 # Policy keys.
1297 f.write('// Registry key names for user and device policies.\n'
1298 'namespace key {\n\n')
1299 for policy in policies:
1300 f.write('extern const char k' + policy.name + '[];\n')
1301 f.write('\n} // namespace key\n\n')
1302
1303 # User policy proto pointers, one struct for each protobuf type.
1304 for protobuf_type in protobuf_types:
1305 _WriteChromeOSPolicyAccessHeader(f, protobuf_type)
1306
1307 f.write('} // namespace policy\n\n'
1308 '#endif // __BINDINGS_POLICY_CONSTANTS_H_\n')
1309
1310
1311 #------------------ Chrome OS policy constants source --------------#
1312
1313 # Writes an array that contains the pointers to the mutable proto field for each
1314 # policy in |policies| of the given |protobuf_type|.
1315 def _WriteChromeOSPolicyAccessSource(policies, f, protobuf_type):
1316 f.write('constexpr %sPolicyAccess k%sPolicyAccess[] = {\n'
1317 % (protobuf_type, protobuf_type))
1318 for policy in policies:
1319 if policy.policy_protobuf_type == protobuf_type:
1320 f.write(' {key::k%s,\n'
1321 ' &em::CloudPolicySettings::mutable_%s},\n'
1322 % (policy.name, policy.name.lower()))
1323 # The list is nullptr-terminated.
1324 f.write(' {nullptr, nullptr},\n'
1325 '};\n\n')
1326
1327
1328 # Writes policy_constants.cc for use in Chrome OS.
1329 def _WriteChromeOSPolicyConstantsSource(policies, os, f, risk_tags):
1330 f.write('#include "bindings/cloud_policy.pb.h"\n'
1331 '#include "bindings/policy_constants.h"\n\n'
1332 'namespace em = enterprise_management;\n\n'
1333 'namespace policy {\n\n')
1334
1335 # Policy keys.
1336 f.write('namespace key {\n\n')
1337 for policy in policies:
1338 f.write('const char k{name}[] = "{name}";\n'.format(name=policy.name))
1339 f.write('\n} // namespace key\n\n')
1340
1341 # User policy proto pointers, one struct for each protobuf type.
1342 supported_user_policies = _GetSupportedUserPolicies(policies)
1343 protobuf_types = _GetProtobufTypes(supported_user_policies)
1344 for protobuf_type in protobuf_types:
1345 _WriteChromeOSPolicyAccessSource(supported_user_policies, f, protobuf_type)
1346
1347 f.write('} // namespace policy\n')
1348
1349
1350 #------------------ app restrictions -------------------------------#
1351
1352 def _WriteAppRestrictions(policies, os, f, risk_tags):
1235 1353
1236 def WriteRestrictionCommon(key): 1354 def WriteRestrictionCommon(key):
1237 f.write(' <restriction\n' 1355 f.write(' <restriction\n'
1238 ' android:key="%s"\n' % key) 1356 ' android:key="%s"\n' % key)
1239 f.write(' android:title="@string/%sTitle"\n' % key) 1357 f.write(' android:title="@string/%sTitle"\n' % key)
1240 f.write(' android:description="@string/%sDesc"\n' % key) 1358 f.write(' android:description="@string/%sDesc"\n' % key)
1241 1359
1242 def WriteItemsDefinition(key): 1360 def WriteItemsDefinition(key):
1243 f.write(' android:entries="@array/%sEntries"\n' % key) 1361 f.write(' android:entries="@array/%sEntries"\n' % key)
1244 f.write(' android:entryValues="@array/%sValues"\n' % key) 1362 f.write(' android:entryValues="@array/%sValues"\n' % key)
(...skipping 12 matching lines...) Expand all
1257 f.write('<restrictions xmlns:android="' 1375 f.write('<restrictions xmlns:android="'
1258 'http://schemas.android.com/apk/res/android">\n\n') 1376 'http://schemas.android.com/apk/res/android">\n\n')
1259 for policy in policies: 1377 for policy in policies:
1260 if (policy.is_supported and policy.restriction_type != 'invalid' and 1378 if (policy.is_supported and policy.restriction_type != 'invalid' and
1261 not policy.is_deprecated and not policy.is_future): 1379 not policy.is_deprecated and not policy.is_future):
1262 WriteAppRestriction(policy) 1380 WriteAppRestriction(policy)
1263 f.write('</restrictions>') 1381 f.write('</restrictions>')
1264 1382
1265 if __name__ == '__main__': 1383 if __name__ == '__main__':
1266 sys.exit(main()) 1384 sys.exit(main())
OLDNEW
« no previous file with comments | « no previous file | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698