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