1#!/usr/bin/env python 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 4# found in the LICENSE file. 5 6from textwrap import TextWrapper 7from grit.format.policy_templates.writers import template_writer 8 9 10TEMPLATE_HEADER="""\ 11// Policy template for Linux. 12// Uncomment the policies you wish to activate and change their values to 13// something useful for your case. The provided values are for reference only 14// and do not provide meaningful defaults! 15{""" 16 17 18HEADER_DELIMETER="""\ 19 //-------------------------------------------------------------------------""" 20 21 22def GetWriter(config): 23 '''Factory method for creating JsonWriter objects. 24 See the constructor of TemplateWriter for description of 25 arguments. 26 ''' 27 return JsonWriter(['linux'], config) 28 29 30class JsonWriter(template_writer.TemplateWriter): 31 '''Class for generating policy files in JSON format (for Linux). The 32 generated files will define all the supported policies with example values 33 set for them. This class is used by PolicyTemplateGenerator to write .json 34 files. 35 ''' 36 37 def PreprocessPolicies(self, policy_list): 38 return self.FlattenGroupsAndSortPolicies(policy_list) 39 40 def WritePolicy(self, policy): 41 example_value = policy['example_value'] 42 if policy['type'] == 'string': 43 example_value_str = '"' + example_value + '"' 44 elif policy['type'] in ('int', 'int-enum', 'dict'): 45 example_value_str = str(example_value) 46 elif policy['type'] == 'list': 47 if example_value == []: 48 example_value_str = '[]' 49 else: 50 example_value_str = '["%s"]' % '", "'.join(example_value) 51 elif policy['type'] == 'main': 52 if example_value == True: 53 example_value_str = 'true' 54 else: 55 example_value_str = 'false' 56 elif policy['type'] == 'string-enum': 57 example_value_str = '"%s"' % example_value; 58 else: 59 raise Exception('unknown policy type %s:' % policy['type']) 60 61 # Add comma to the end of the previous line. 62 if not self._first_written: 63 self._out[-2] += ',' 64 65 line = ' // %s' % policy['caption'] 66 self._out.append(line) 67 self._out.append(HEADER_DELIMETER) 68 description = self._text_wrapper.wrap(policy['desc']) 69 self._out += description; 70 line = ' //"%s": %s' % (policy['name'], example_value_str) 71 self._out.append('') 72 self._out.append(line) 73 self._out.append('') 74 75 self._first_written = False 76 77 def BeginTemplate(self): 78 self._out.append(TEMPLATE_HEADER) 79 80 def EndTemplate(self): 81 self._out.append('}') 82 83 def Init(self): 84 self._out = [] 85 # The following boolean member is true until the first policy is written. 86 self._first_written = True 87 # Create the TextWrapper object once. 88 self._text_wrapper = TextWrapper( 89 initial_indent = ' // ', 90 subsequent_indent = ' // ', 91 break_long_words = False, 92 width = 80) 93 94 def GetTemplateText(self): 95 return '\n'.join(self._out) 96