diff options
author | gfeher@chromium.org <gfeher@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2011-01-14 08:27:44 +0000 |
---|---|---|
committer | gfeher@chromium.org <gfeher@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2011-01-14 08:27:44 +0000 |
commit | 205dd98f52c490ccc5a4e58ab770379d1250e9f6 (patch) | |
tree | 49c8cdb2f2e9d0e0ad20599d7cb1440b7af6b740 /tools | |
parent | a4be7f9fccc61e3e5c478f26bf24e9670202bc5e (diff) | |
download | chromium_src-205dd98f52c490ccc5a4e58ab770379d1250e9f6.zip chromium_src-205dd98f52c490ccc5a4e58ab770379d1250e9f6.tar.gz chromium_src-205dd98f52c490ccc5a4e58ab770379d1250e9f6.tar.bz2 |
Integrate user strings into the JSON policy template file
The new concept is the following: policy_templates.json contains all the data necessary to generate templates: policy names, English captions, descriptions, etc. This gets translated the following GRIT gatherer: policy_json.py. The text of the translated JSON file is then picked up, parsed, and passed to the writers by template_formatter.py.
BUG=64898
TEST=PolicyJsonUnittest.*
Review URL: http://codereview.chromium.org/6134006
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@71421 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'tools')
30 files changed, 1200 insertions, 775 deletions
diff --git a/tools/grit/grit/format/policy_templates/policy_template_generator.py b/tools/grit/grit/format/policy_templates/policy_template_generator.py index c80bd64..caf9019 100644 --- a/tools/grit/grit/format/policy_templates/policy_template_generator.py +++ b/tools/grit/grit/format/policy_templates/policy_template_generator.py @@ -15,7 +15,19 @@ class PolicyTemplateGenerator: this data to policy template files using TemplateWriter objects. ''' - def __init__(self, messages, policy_definitions): + def _ImportMessage(self, msg_txt): + # Replace the placeholder of app name. + msg_txt = msg_txt.replace('$1', self._config['app_name']) + msg_txt = msg_txt.replace('$3', self._config['frame_name']) + # Replace other placeholders. + for placeholder in self._policy_data['placeholders']: + msg_txt = msg_txt.replace(placeholder['key'], placeholder['value']) + # Strip spaces and escape newlines. + lines = msg_txt.split('\n') + lines = [line.strip() for line in lines] + return "\n".join(lines) + + def __init__(self, config, policy_data): '''Initializes this object with all the data necessary to output a policy template. @@ -29,9 +41,14 @@ class PolicyTemplateGenerator: content. ''' # List of all the policies: - self._policy_definitions = copy.deepcopy(policy_definitions) + self._policy_data = copy.deepcopy(policy_data) # Localized messages to be inserted to the policy_definitions structure: - self._messages = messages + self._messages = self._policy_data['messages'] + self._config = config + for key in self._messages.keys(): + self._messages[key]['text'] = self._ImportMessage( + self._messages[key]['text']) + self._policy_definitions = self._policy_data['policy_definitions'] self._ProcessPolicyList(self._policy_definitions) def _ProcessSupportedOn(self, supported_on): @@ -84,55 +101,31 @@ class PolicyTemplateGenerator: }) return result - def _AddMessageToItem(self, item_name, item, message_name, default=None): - '''Adds a localized message string to an item of the policy data structure - - Args: - item_name: The base of the grd name of the item. - item: The policy, group, or enum item. - message_name: Identifier of the message: 'desc', 'caption' or 'label'. - default: If this is specified and the message is not found for item, - then this string will be added to the item. - - Raises: - Exception() if the message string was not found and no default was - specified. - ''' - # The keys for the item's messages in self._messages: - long_message_name = ('IDS_POLICY_%s_%s' % - (item_name.upper(), message_name.upper())) - # Copy the messages from self._messages to item: - if long_message_name in self._messages: - item[message_name] = self._messages[long_message_name] - elif default != None: - item[message_name] = default - else: - raise Exception('No localized message for %s (missing %s).' % - (item_name, long_message_name)) - def _ProcessPolicy(self, policy): - '''Adds localized message strings to a policy or group. + '''Processes localized message strings in a policy or a group. Also breaks up the content of 'supported_on' attribute into a list. Args: policy: The data structure of the policy or group, that will get message strings here. ''' - self._AddMessageToItem(policy['name'], policy, 'caption') - self._AddMessageToItem(policy['name'], policy, 'desc') - if policy['type'] != 'group': - # Real policies (that are not groups) might also have an optional - # 'label', that defaults to 'caption'. - self._AddMessageToItem( - policy['name'], policy, 'label', policy['caption']) - policy['supported_on'] = self._ProcessSupportedOn( - policy['supported_on']) + policy['desc'] = self._ImportMessage(policy['desc']) + policy['caption'] = self._ImportMessage(policy['caption']) + if 'label' in policy: + policy['label'] = self._ImportMessage(policy['label']) + if policy['type'] == 'group': self._ProcessPolicyList(policy['policies']) elif policy['type'] in ('string-enum', 'int-enum'): # Iterate through all the items of an enum-type policy, and add captions. for item in policy['items']: - self._AddMessageToItem('ENUM_' + item['name'], item, 'caption') + item['caption'] = self._ImportMessage(item['caption']) + if policy['type'] != 'group': + if not 'label' in policy: + # If 'label' is not specified, then it defaults to 'caption': + policy['label'] = policy['caption'] + policy['supported_on'] = self._ProcessSupportedOn( + policy['supported_on']) def _ProcessPolicyList(self, policy_list): '''Adds localized message strings to each item in a list of policies and @@ -157,4 +150,4 @@ class PolicyTemplateGenerator: Returns: The text of the generated template. ''' - return template_writer.WriteTemplate(self._policy_definitions) + return template_writer.WriteTemplate(self._policy_data) diff --git a/tools/grit/grit/format/policy_templates/policy_template_generator_unittest.py b/tools/grit/grit/format/policy_templates/policy_template_generator_unittest.py index fe27216..a5dba3a 100644 --- a/tools/grit/grit/format/policy_templates/policy_template_generator_unittest.py +++ b/tools/grit/grit/format/policy_templates/policy_template_generator_unittest.py @@ -15,20 +15,10 @@ from grit.format.policy_templates.writers import mock_writer from grit.format.policy_templates.writers import template_writer -class MessagesMock: - '''A mock dictionary that contains "all the keys". Used for tests - where the handling of GUI messages is irrelevant. - ''' - def __getitem__(self, key): - return '' - def __contains__(self, key): - return True - - class PolicyTemplateGeneratorUnittest(unittest.TestCase): '''Unit tests for policy_template_generator.py.''' - def do_test(self, messages, policy_definitions, writer): + def do_test(self, policy_data, writer): '''Executes a test case. Creates and invokes an instance of PolicyTemplateGenerator with @@ -39,16 +29,25 @@ class PolicyTemplateGeneratorUnittest(unittest.TestCase): test output. Args: - messages: The dictionary of localized messages. - policy_definitions: The list of policies and groups as it would be + policy_data: The list of policies and groups as it would be loaded from policy_templates.json. writer: A writer used for this test. It is usually derived from mock_writer.MockWriter. ''' writer.tester = self + config = { + 'app_name': '_app_name', + 'frame_name': '_frame_name', + } + if not 'messages' in policy_data: + policy_data['messages'] = {} + if not 'placeholders' in policy_data: + policy_data['placeholders'] = [] + if not 'policy_definitions' in policy_data: + policy_data['policy_definitions'] = [] policy_generator = policy_template_generator.PolicyTemplateGenerator( - messages, - policy_definitions) + config, + policy_data) res = policy_generator.GetTemplateText(writer) writer.Test() return res @@ -71,16 +70,21 @@ class PolicyTemplateGeneratorUnittest(unittest.TestCase): def Test(self): self.tester.assertEquals(self.log, 'init;prepare;begin;end;get_text;') - result = self.do_test({}, [], LocalMockWriter()) + result = self.do_test({}, LocalMockWriter()) self.assertEquals(result, 'writer_result_string') def testEmptyGroups(self): # Test that empty policy groups are not passed to the writer. - policies_mock = [ - {'name': 'Group1', 'type': 'group', 'policies': []}, - {'name': 'Group2', 'type': 'group', 'policies': []}, - {'name': 'Group3', 'type': 'group', 'policies': []}, - ] + policies_mock = { + 'policy_definitions': [ + {'name': 'Group1', 'type': 'group', 'policies': [], + 'desc': '', 'caption': ''}, + {'name': 'Group2', 'type': 'group', 'policies': [], + 'desc': '', 'caption': ''}, + {'name': 'Group3', 'type': 'group', 'policies': [], + 'desc': '', 'caption': ''}, + ] + } class LocalMockWriter(mock_writer.MockWriter): def __init__(self): self.log = '' @@ -90,24 +94,32 @@ class PolicyTemplateGeneratorUnittest(unittest.TestCase): self.log += ']' def Test(self): self.tester.assertEquals(self.log, '') - self.do_test(MessagesMock(), policies_mock, LocalMockWriter()) + self.do_test(policies_mock, LocalMockWriter()) def testGroups(self): # Test that policy groups are passed to the writer in the correct order. - policies_mock = [ - { - 'name': 'Group1', 'type': 'group', - 'policies': [{'name': 'TAG1', 'type': 'mock', 'supported_on': []}] - }, - { - 'name': 'Group2', 'type': 'group', - 'policies': [{'name': 'TAG2', 'type': 'mock', 'supported_on': []}] - }, - { - 'name': 'Group3', 'type': 'group', - 'policies': [{'name': 'TAG3', 'type': 'mock', 'supported_on': []}] - }, - ] + policies_mock = { + 'policy_definitions': [ + { + 'name': 'Group1', 'type': 'group', + 'caption': '', 'desc': '', + 'policies': [{'name': 'TAG1', 'type': 'mock', 'supported_on': [], + 'caption': '', 'desc': ''}] + }, + { + 'name': 'Group2', 'type': 'group', + 'caption': '', 'desc': '', + 'policies': [{'name': 'TAG2', 'type': 'mock', 'supported_on': [], + 'caption': '', 'desc': ''}] + }, + { + 'name': 'Group3', 'type': 'group', + 'caption': '', 'desc': '', + 'policies': [{'name': 'TAG3', 'type': 'mock', 'supported_on': [], + 'caption': '', 'desc': ''}] + }, + ] + } class LocalMockWriter(mock_writer.MockWriter): def __init__(self): self.log = '' @@ -117,51 +129,36 @@ class PolicyTemplateGeneratorUnittest(unittest.TestCase): self.log += ']' def Test(self): self.tester.assertEquals(self.log, '[TAG1][TAG2][TAG3]') - self.do_test(MessagesMock(), policies_mock, LocalMockWriter()) - - def testGroupTexts(self): - # Test that GUI messages are assigned correctly to policy groups. - messages_mock = { - 'IDS_POLICY_GROUP1_CAPTION': 'string1', - 'IDS_POLICY_GROUP1_DESC': 'string2', - 'IDS_POLICY_GROUP2_CAPTION': 'string3', - 'IDS_POLICY_GROUP2_DESC': 'string4', - } - policy_defs_mock = [ - {'name': 'Group1', 'type': 'group', 'policies': []}, - {'name': 'Group2', 'type': 'group', 'policies': []}, - ] - class LocalMockWriter(mock_writer.MockWriter): - def BeginPolicyGroup(self, group): - if group['name'] == 'Group1': - self.tester.assertEquals(group['caption'], 'string1') - self.tester.assertEquals(group['desc'], 'string2') - elif group['name'] == 'Group2': - self.tester.assertEquals(group['caption'], 'string3') - self.tester.assertEquals(group['desc'], 'string4') - else: - self.tester.fail() - self.do_test(messages_mock, policy_defs_mock, LocalMockWriter()) + self.do_test(policies_mock, LocalMockWriter()) def testPolicies(self): # Test that policies are passed to the writer in the correct order. - policy_defs_mock = [ - { - 'name': 'Group1', - 'type': 'group', - 'policies': [ - {'name': 'Group1Policy1', 'type': 'string', 'supported_on': []}, - {'name': 'Group1Policy2', 'type': 'string', 'supported_on': []}, - ] - }, - { - 'name': 'Group2', - 'type': 'group', - 'policies': [ - {'name': 'Group2Policy3', 'type': 'string', 'supported_on': []}, - ] - } - ] + policy_defs_mock = { + 'policy_definitions': [ + { + 'name': 'Group1', + 'type': 'group', + 'caption': '', + 'desc': '', + 'policies': [ + {'name': 'Group1Policy1', 'type': 'string', 'supported_on': [], + 'caption': '', 'desc': ''}, + {'name': 'Group1Policy2', 'type': 'string', 'supported_on': [], + 'caption': '', 'desc': ''}, + ] + }, + { + 'name': 'Group2', + 'type': 'group', + 'caption': '', + 'desc': '', + 'policies': [ + {'name': 'Group2Policy3', 'type': 'string', 'supported_on': [], + 'caption': '', 'desc': ''}, + ] + } + ] + } class LocalMockWriter(mock_writer.MockWriter): def __init__(self): self.policy_name = None @@ -177,130 +174,146 @@ class PolicyTemplateGeneratorUnittest(unittest.TestCase): self.tester.assertEquals( self.policy_list, ['Group1Policy1', 'Group1Policy2', 'Group2Policy3']) - self.do_test(MessagesMock(), policy_defs_mock, LocalMockWriter()) + self.do_test( policy_defs_mock, LocalMockWriter()) def testPolicyTexts(self): - # Test that GUI messages are assigned correctly to policies. - messages_mock = { - 'IDS_POLICY_POLICY1_CAPTION': 'string1', - 'IDS_POLICY_POLICY1_DESC': 'string2', - 'IDS_POLICY_POLICY2_CAPTION': 'string3', - 'IDS_POLICY_POLICY2_DESC': 'string4', - 'IDS_POLICY_GROUP1_CAPTION': '', - 'IDS_POLICY_GROUP1_DESC': '', + # Test that GUI messages of policies all get placeholders replaced. + policy_data_mock = { + 'policy_definitions': [ + { + 'name': 'Group1', + 'type': 'group', + 'desc': '', + 'caption': '', + 'policies': [ + { + 'name': 'Policy1', + 'caption': '1. app_name -- $1', + 'label': '2. placeholder -- $2', + 'desc': '3. frame_name -- $3', + 'type': 'string', + 'supported_on': [] + }, + ] + } + ], + 'placeholders': [ + { + 'key': '$2', + 'value': 'Placeholder nr. 2.' + } + ], } - policy_defs_mock = [ - { - 'name': 'Group1', - 'type': 'group', - 'policies': [ - {'name': 'Policy1', 'type': 'string', 'supported_on': []}, - {'name': 'Policy2', 'type': 'string', 'supported_on': []} - ] - } - ] class LocalMockWriter(mock_writer.MockWriter): def WritePolicy(self, policy): if policy['name'] == 'Policy1': - self.tester.assertEquals(policy['caption'], 'string1') - self.tester.assertEquals(policy['desc'], 'string2') - elif policy['name'] == 'Policy2': - self.tester.assertEquals(policy['caption'], 'string3') - self.tester.assertEquals(policy['desc'], 'string4') + self.tester.assertEquals(policy['caption'], + '1. app_name -- _app_name') + self.tester.assertEquals(policy['label'], + '2. placeholder -- Placeholder nr. 2.') + self.tester.assertEquals(policy['desc'], + '3. frame_name -- _frame_name') + elif policy['name'] == 'Group1': + pass else: self.tester.fail() - self.do_test(messages_mock, policy_defs_mock, LocalMockWriter()) + self.do_test(policy_data_mock, LocalMockWriter()) def testIntEnumTexts(self): - # Test that GUI messages are assigned correctly to enums + # Test that GUI messages are assigned correctly to int-enums # (aka dropdown menus). - messages_mock = { - 'IDS_POLICY_ENUM_ITEM1_CAPTION': 'string1', - 'IDS_POLICY_ENUM_ITEM2_CAPTION': 'string2', - 'IDS_POLICY_ENUM_ITEM3_CAPTION': 'string3', - 'IDS_POLICY_POLICY1_CAPTION': '', - 'IDS_POLICY_POLICY1_DESC': '', - + policy_defs_mock = { + 'policy_definitions': [{ + 'name': 'Policy1', + 'type': 'int-enum', + 'caption': '', 'desc': '', + 'supported_on': [], + 'items': [ + {'name': 'item1', 'value': 0, 'caption': 'string1', 'desc': ''}, + {'name': 'item2', 'value': 1, 'caption': 'string2', 'desc': ''}, + {'name': 'item3', 'value': 3, 'caption': 'string3', 'desc': ''}, + ] + }] } - policy_defs_mock = [{ - 'name': 'Policy1', - 'type': 'int-enum', - 'supported_on': [], - 'items': [ - {'name': 'item1', 'value': 0}, - {'name': 'item2', 'value': 1}, - {'name': 'item3', 'value': 3}, - ] - }] class LocalMockWriter(mock_writer.MockWriter): def WritePolicy(self, policy): self.tester.assertEquals(policy['items'][0]['caption'], 'string1') self.tester.assertEquals(policy['items'][1]['caption'], 'string2') self.tester.assertEquals(policy['items'][2]['caption'], 'string3') - self.do_test(messages_mock, policy_defs_mock, LocalMockWriter()) + self.do_test(policy_defs_mock, LocalMockWriter()) def testStringEnumTexts(self): - # Test that GUI messages are assigned correctly to enums + # Test that GUI messages are assigned correctly to string-enums # (aka dropdown menus). - messages_mock = { - 'IDS_POLICY_ENUM_ITEM1_CAPTION': 'string1', - 'IDS_POLICY_ENUM_ITEM2_CAPTION': 'string2', - 'IDS_POLICY_ENUM_ITEM3_CAPTION': 'string3', - 'IDS_POLICY_POLICY1_CAPTION': '', - 'IDS_POLICY_POLICY1_DESC': '', - + policy_data_mock = { + 'policy_definitions': [{ + 'name': 'Policy1', + 'type': 'string-enum', + 'caption': '', 'desc': '', + 'supported_on': [], + 'items': [ + {'name': 'item1', 'value': 'one', 'caption': 'string1', 'desc': ''}, + {'name': 'item2', 'value': 'two', 'caption': 'string2', 'desc': ''}, + {'name': 'item3', 'value': 'three', 'caption': 'string3', 'desc': ''}, + ] + }] } - policy_defs_mock = [{ - 'name': 'Policy1', - 'type': 'string-enum', - 'supported_on': [], - 'items': [ - {'name': 'item1', 'value': 'one'}, - {'name': 'item2', 'value': 'two'}, - {'name': 'item3', 'value': 'three'}, - ] - }] - class LocalMockWriter(mock_writer.MockWriter): def WritePolicy(self, policy): self.tester.assertEquals(policy['items'][0]['caption'], 'string1') self.tester.assertEquals(policy['items'][1]['caption'], 'string2') self.tester.assertEquals(policy['items'][2]['caption'], 'string3') - self.do_test(messages_mock, policy_defs_mock, LocalMockWriter()) + self.do_test(policy_data_mock, LocalMockWriter()) def testPolicyFiltering(self): # Test that policies are filtered correctly based on their annotations. - policy_defs_mock = [{ - 'name': 'Group1', - 'type': 'group', - 'policies': [ - { - 'name': 'Group1Policy1', - 'type': 'string', - 'supported_on': ['chrome.aaa:8-', 'chrome.bbb:8-', 'chrome.ccc:8-'] - }, - { - 'name': 'Group1Policy2', - 'type': 'string', - 'supported_on': ['chrome.ddd:8-'] - }, - ] - }, { - 'name': 'Group2', - 'type': 'group', - 'policies': [ - { - 'name': 'Group2Policy3', - 'type': 'string', + policy_data_mock = { + 'policy_definitions': [ + { + 'name': 'Group1', + 'type': 'group', + 'caption': '', + 'desc': '', + 'policies': [ + { + 'name': 'Group1Policy1', + 'type': 'string', + 'caption': '', + 'desc': '', + 'supported_on': ['chrome.aaa:8-', 'chrome.bbb:8-', 'chrome.ccc:8-'] + }, + { + 'name': 'Group1Policy2', + 'type': 'string', + 'caption': '', + 'desc': '', + 'supported_on': ['chrome.ddd:8-'] + }, + ] + }, { + 'name': 'Group2', + 'type': 'group', + 'caption': '', + 'desc': '', + 'policies': [ + { + 'name': 'Group2Policy3', + 'type': 'string', + 'caption': '', + 'desc': '', + 'supported_on': ['chrome.eee:8-'] + }, + ] + }, { + 'name': 'SinglePolicy', + 'type': 'int', + 'caption': '', + 'desc': '', 'supported_on': ['chrome.eee:8-'] - }, + } ] - }, { - 'name': 'SinglePolicy', - 'type': 'int', - 'supported_on': ['chrome.eee:8-'] - }] + } # This writer accumulates the list of policies it is asked to write. # This list is stored in the result_list member variable and can # be used later for assertions. @@ -322,14 +335,14 @@ class PolicyTemplateGeneratorUnittest(unittest.TestCase): return template_writer.TemplateWriter.IsPolicySupported(self, policy) local_mock_writer = LocalMockWriter(['eee']) - self.do_test(MessagesMock(), policy_defs_mock, local_mock_writer) + self.do_test(policy_data_mock, local_mock_writer) # Test that only policies of platform 'eee' were written: self.assertEquals( local_mock_writer.result_list, ['begin_Group2', 'Group2Policy3', 'end_group', 'SinglePolicy']) local_mock_writer = LocalMockWriter(['ddd', 'bbb']) - self.do_test(MessagesMock(), policy_defs_mock, local_mock_writer) + self.do_test(policy_data_mock, local_mock_writer) # Test that only policies of platforms 'ddd' and 'bbb' were written: self.assertEquals( local_mock_writer.result_list, @@ -337,10 +350,14 @@ class PolicyTemplateGeneratorUnittest(unittest.TestCase): def testSortingInvoked(self): # Tests that policy-sorting happens before passing policies to the writer. - policy_defs = [ - {'name': 'zp', 'type': 'string', 'supported_on': []}, - {'name': 'ap', 'type': 'string', 'supported_on': []} - ] + policy_data = { + 'policy_definitions': [ + {'name': 'zp', 'type': 'string', 'supported_on': [], + 'caption': '', 'desc': ''}, + {'name': 'ap', 'type': 'string', 'supported_on': [], + 'caption': '', 'desc': ''}, + ] + } class LocalMockWriter(mock_writer.MockWriter): def __init__(self): self.result_list = [] @@ -350,7 +367,7 @@ class PolicyTemplateGeneratorUnittest(unittest.TestCase): self.tester.assertEquals( self.result_list, ['ap', 'zp']) - self.do_test(MessagesMock(), policy_defs, LocalMockWriter()) + self.do_test(policy_data, LocalMockWriter()) if __name__ == '__main__': diff --git a/tools/grit/grit/format/policy_templates/template_formatter.py b/tools/grit/grit/format/policy_templates/template_formatter.py index 4fd28eb..0e304af 100644 --- a/tools/grit/grit/format/policy_templates/template_formatter.py +++ b/tools/grit/grit/format/policy_templates/template_formatter.py @@ -1,4 +1,4 @@ -# Copyright (c) 2010 The Chromium Authors. All rights reserved. +# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. @@ -75,34 +75,12 @@ class TemplateFormatter(interface.ItemFormatter): to __init__() and Format(). ''' policy_generator = policy_template_generator.PolicyTemplateGenerator( - self._messages, - self._policy_data['policy_definitions']) - writer = self._writer_module.GetWriter(self._config, self._messages) + self._config, + self._policy_data) + writer = self._writer_module.GetWriter(self._config) str = policy_generator.GetTemplateText(writer) return str - def _ImportMessage(self, message): - '''Takes a grit message node and adds its translated content to - self._messages. - - Args: - message: A <message> node in the grit tree. - ''' - msg_name = message.GetTextualIds()[0] - # Get translation of message. - msg_txt = message.Translate(self._lang) - # Replace the placeholder of app name. - msg_txt = msg_txt.replace('$1', self._config['app_name']) - msg_txt = msg_txt.replace('$3', self._config['frame_name']) - # Replace other placeholders. - for placeholder in self._policy_data['placeholders']: - msg_txt = msg_txt.replace(placeholder['key'], placeholder['value']) - # Strip spaces and escape newlines. - lines = msg_txt.split('\n') - lines = [line.strip() for line in lines] - msg_txt = "\n".join(lines) - self._messages[msg_name] = msg_txt - def _ParseGritNodes(self, item): '''Collects the necessary information from the grit tree: the message strings and the policy definitions. @@ -116,8 +94,7 @@ class TemplateFormatter(interface.ItemFormatter): if (isinstance(item, structure.StructureNode) and item.attrs['type'] == 'policy_template_metafile'): assert self._policy_data == None - self._policy_data = item.gatherer.GetData() - elif (isinstance(item, message.MessageNode)): - self._ImportMessage(item) + json_text = item.gatherer.Translate(self._lang) + self._policy_data = eval(json_text) for child in item.children: self._ParseGritNodes(child) diff --git a/tools/grit/grit/format/policy_templates/writer_configuration.py b/tools/grit/grit/format/policy_templates/writer_configuration.py index 11bcf54..bc0d4b7 100644 --- a/tools/grit/grit/format/policy_templates/writer_configuration.py +++ b/tools/grit/grit/format/policy_templates/writer_configuration.py @@ -1,4 +1,4 @@ -# Copyright (c) 2010 The Chromium Authors. All rights reserved. +# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. @@ -45,7 +45,6 @@ def GetConfigurationForBuild(defines): raise Exception('Unknown build') config['win_group_policy_class'] = 'Machine' config['win_supported_os'] = 'SUPPORTED_WINXPSP2' - config['win_supported_os_msg'] = 'IDS_POLICY_WIN_SUPPORTED_WINXPSP2' if 'mac_bundle_id' in defines: config['mac_bundle_id'] = defines['mac_bundle_id'] return config diff --git a/tools/grit/grit/format/policy_templates/writers/adm_writer.py b/tools/grit/grit/format/policy_templates/writers/adm_writer.py index c3df88c..b55ede1 100644 --- a/tools/grit/grit/format/policy_templates/writers/adm_writer.py +++ b/tools/grit/grit/format/policy_templates/writers/adm_writer.py @@ -6,12 +6,12 @@ from grit.format.policy_templates.writers import template_writer -def GetWriter(config, messages): +def GetWriter(config): '''Factory method for creating AdmWriter objects. See the constructor of TemplateWriter for description of arguments. ''' - return AdmWriter(['win'], config, messages) + return AdmWriter(['win'], config) class AdmWriter(template_writer.TemplateWriter): @@ -125,7 +125,7 @@ class AdmWriter(template_writer.TemplateWriter): def BeginTemplate(self): category_path = self.config['win_category_path'] self._AddGuiString(self.config['win_supported_os'], - self.messages[self.config['win_supported_os_msg']]) + self.messages['win_supported_winxpsp2']['text']) self._PrintLine( 'CLASS ' + self.config['win_group_policy_class'].upper(), 1) diff --git a/tools/grit/grit/format/policy_templates/writers/adm_writer_unittest.py b/tools/grit/grit/format/policy_templates/writers/adm_writer_unittest.py index 5fb690c..6495862 100644 --- a/tools/grit/grit/format/policy_templates/writers/adm_writer_unittest.py +++ b/tools/grit/grit/format/policy_templates/writers/adm_writer_unittest.py @@ -44,12 +44,13 @@ class AdmWriterUnittest(writer_unittest_common.WriterUnittestCommon): { 'policy_definitions': [], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_WIN_SUPPORTED_WINXPSP2">At least "Windows 3.11</message> - </messages> - ''') - output = self.GetOutput(grd, 'fr', {'_chromium': '1', }, 'adm', 'en') + 'messages': { + 'win_supported_winxpsp2': { + 'text': 'At least "Windows 3.11', 'desc': 'blah' + } + } + }''') + output = self.GetOutput(grd, 'fr', {'_chromium': '1',}, 'adm', 'en') expected_output = '''CLASS MACHINE CATEGORY !!chromium KEYNAME "Software\\Policies\\Chromium" @@ -69,17 +70,18 @@ chromium="Chromium"''' { 'name': 'MainPolicy', 'type': 'main', - 'supported_on': ['chrome.win:8-'] + 'supported_on': ['chrome.win:8-'], + 'caption': 'Caption of main.', + 'desc': 'Description of main.', }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_MAINPOLICY_CAPTION">Caption of main.</message> - <message name="IDS_POLICY_MAINPOLICY_DESC">Description of main.</message> - <message name="IDS_POLICY_WIN_SUPPORTED_WINXPSP2">At least Windows 3.12</message> - </messages> - ''') + 'messages': { + 'win_supported_winxpsp2': { + 'text': 'At least Windows 3.12', 'desc': 'blah' + } + } + }''') output = self.GetOutput(grd, 'fr', {'_google_chrome' : '1'}, 'adm', 'en') expected_output = '''CLASS MACHINE CATEGORY !!google @@ -115,18 +117,19 @@ MainPolicy_Explain="Description of main."''' { 'name': 'StringPolicy', 'type': 'string', - 'supported_on': ['chrome.win:8-'] + 'supported_on': ['chrome.win:8-'], + 'desc': """Description of group. +With a newline.""", + 'caption': 'Caption of policy.', }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_STRINGPOLICY_CAPTION">Caption of policy.</message> - <message name="IDS_POLICY_STRINGPOLICY_DESC">Description of group. -With a newline.</message> - <message name="IDS_POLICY_WIN_SUPPORTED_WINXPSP2">At least Windows 3.13</message> - </messages> - ''') + 'messages': { + 'win_supported_winxpsp2': { + 'text': 'At least Windows 3.13', 'desc': 'blah' + } + } + }''') output = self.GetOutput(grd, 'fr', {'_chromium' : '1'}, 'adm', 'en') expected_output = '''CLASS MACHINE CATEGORY !!chromium @@ -162,18 +165,18 @@ StringPolicy_Part="Caption of policy." { 'name': 'IntPolicy', 'type': 'int', + 'caption': 'Caption of policy.', + 'desc': 'Description of policy.', 'supported_on': ['chrome.win:8-'] }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_INTPOLICY_CAPTION">Caption of policy.</message> - <message name="IDS_POLICY_INTPOLICY_DESC">Description of group. -With a newline.</message> - <message name="IDS_POLICY_WIN_SUPPORTED_WINXPSP2">At least Windows 3.13</message> - </messages> - ''') + 'messages': { + 'win_supported_winxpsp2': { + 'text': 'At least Windows 3.13', 'desc': 'blah' + } + } + }''') output = self.GetOutput(grd, 'fr', {'_chromium' : '1'}, 'adm', 'en') expected_output = '''CLASS MACHINE CATEGORY !!chromium @@ -196,7 +199,7 @@ With a newline.</message> SUPPORTED_WINXPSP2="At least Windows 3.13" chromium="Chromium" IntPolicy_Policy="Caption of policy." -IntPolicy_Explain="Description of group.\\nWith a newline." +IntPolicy_Explain="Description of policy." IntPolicy_Part="Caption of policy." ''' self.CompareOutputs(output, expected_output) @@ -210,22 +213,29 @@ IntPolicy_Part="Caption of policy." 'name': 'EnumPolicy', 'type': 'int-enum', 'items': [ - {'name': 'ProxyServerDisabled', 'value': 0}, - {'name': 'ProxyServerAutoDetect', 'value': 1}, + { + 'name': 'ProxyServerDisabled', + 'value': 0, + 'caption': 'Option1', + }, + { + 'name': 'ProxyServerAutoDetect', + 'value': 1, + 'caption': 'Option2', + }, ], + 'desc': 'Description of policy.', + 'caption': 'Caption of policy.', 'supported_on': ['chrome.win:8-'] }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_ENUMPOLICY_CAPTION">Caption of policy.</message> - <message name="IDS_POLICY_ENUMPOLICY_DESC">Description of policy.</message> - <message name="IDS_POLICY_ENUM_PROXYSERVERDISABLED_CAPTION">Option1</message> - <message name="IDS_POLICY_ENUM_PROXYSERVERAUTODETECT_CAPTION">Option2</message> - <message name="IDS_POLICY_WIN_SUPPORTED_WINXPSP2">At least Windows 3.14</message> - </messages> - ''') + 'messages': { + 'win_supported_winxpsp2': { + 'text': 'At least Windows 3.14', 'desc': 'blah' + } + } + }''') output = self.GetOutput(grd, 'fr', {'_google_chrome': '1'}, 'adm', 'en') expected_output = '''CLASS MACHINE CATEGORY !!google @@ -270,23 +280,24 @@ ProxyServerAutoDetect_DropDown="Option2" { 'name': 'EnumPolicy', 'type': 'string-enum', + 'caption': 'Caption of policy.', + 'desc': 'Description of policy.', 'items': [ - {'name': 'ProxyServerDisabled', 'value': 'one'}, - {'name': 'ProxyServerAutoDetect', 'value': 'two'}, + {'name': 'ProxyServerDisabled', 'value': 'one', + 'caption': 'Option1'}, + {'name': 'ProxyServerAutoDetect', 'value': 'two', + 'caption': 'Option2'}, ], 'supported_on': ['chrome.win:8-'] }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_ENUMPOLICY_CAPTION">Caption of policy.</message> - <message name="IDS_POLICY_ENUMPOLICY_DESC">Description of policy.</message> - <message name="IDS_POLICY_ENUM_PROXYSERVERDISABLED_CAPTION">Option1</message> - <message name="IDS_POLICY_ENUM_PROXYSERVERAUTODETECT_CAPTION">Option2</message> - <message name="IDS_POLICY_WIN_SUPPORTED_WINXPSP2">At least Windows 3.14</message> - </messages> - ''') + 'messages': { + 'win_supported_winxpsp2': { + 'text': 'At least Windows 3.14', 'desc': 'blah' + } + } + }''') output = self.GetOutput(grd, 'fr', {'_google_chrome': '1'}, 'adm', 'en') expected_output = '''CLASS MACHINE CATEGORY !!google @@ -331,19 +342,20 @@ ProxyServerAutoDetect_DropDown="Option2" { 'name': 'ListPolicy', 'type': 'list', - 'supported_on': ['chrome.win:8-'] + 'supported_on': ['chrome.win:8-'], + 'desc': """Description of list policy. +With a newline.""", + 'caption': 'Caption of list policy.', + 'label': 'Label of list policy.' }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_LISTPOLICY_DESC">Description of list policy. -With a newline.</message> - <message name="IDS_POLICY_LISTPOLICY_CAPTION">Caption of list policy.</message> - <message name="IDS_POLICY_LISTPOLICY_LABEL">Value caption of list policy.</message> - <message name="IDS_POLICY_WIN_SUPPORTED_WINXPSP2">At least Windows 3.15</message> - </messages> - ''') + 'messages': { + 'win_supported_winxpsp2': { + 'text': 'At least Windows 3.15', 'desc': 'blah' + } + }, + }''') output = self.GetOutput(grd, 'fr', {'_chromium' : '1'}, 'adm', 'en') expected_output = '''CLASS MACHINE CATEGORY !!chromium @@ -368,7 +380,7 @@ SUPPORTED_WINXPSP2="At least Windows 3.15" chromium="Chromium" ListPolicy_Policy="Caption of list policy." ListPolicy_Explain="Description of list policy.\\nWith a newline." -ListPolicy_Part="Value caption of list policy." +ListPolicy_Part="Label of list policy." ''' self.CompareOutputs(output, expected_output) @@ -384,20 +396,21 @@ ListPolicy_Part="Value caption of list policy." 'policies': [{ 'name': 'NonWinPolicy', 'type': 'list', - 'supported_on': ['chrome.linux:8-', 'chrome.mac:8-'] + 'supported_on': ['chrome.linux:8-', 'chrome.mac:8-'], + 'caption': 'Caption of list policy.', + 'desc': 'Desc of list policy.', }], + 'caption': 'Group caption.', + 'desc': 'Group description.', }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_NONWINGROUP_CAPTION">Group caption.</message> - <message name="IDS_POLICY_NONWINGROUP_DESC">Group description.</message> - <message name="IDS_POLICY_NONWINPOLICY_CAPTION">Caption of list policy.</message> - <message name="IDS_POLICY_NONWINPOLICY_DESC">Desc of list policy.</message> - <message name="IDS_POLICY_WIN_SUPPORTED_WINXPSP2">At least Windows 3.16</message> - </messages> - ''') + 'messages': { + 'win_supported_winxpsp2': { + 'text': 'At least Windows 3.16', 'desc': 'blah' + } + } + }''') output = self.GetOutput(grd, 'fr', {'_chromium' : '1'}, 'adm', 'en') expected_output = '''CLASS MACHINE CATEGORY !!chromium @@ -419,31 +432,32 @@ chromium="Chromium" { 'name': 'Group1', 'type': 'group', + 'desc': 'Description of group.', + 'caption': 'Caption of group.', 'policies': [{ 'name': 'Policy1', 'type': 'list', - 'supported_on': ['chrome.win:8-'] + 'supported_on': ['chrome.win:8-'], + 'caption': 'Caption of policy1.', + 'desc': """Description of policy1. +With a newline.""" },{ 'name': 'Policy2', 'type': 'string', - 'supported_on': ['chrome.win:8-'] + 'supported_on': ['chrome.win:8-'], + 'caption': 'Caption of policy2.', + 'desc': """Description of policy2. +With a newline.""" }], }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_GROUP1_CAPTION">Caption of group.</message> - <message name="IDS_POLICY_GROUP1_DESC">Description of group.</message> - <message name="IDS_POLICY_POLICY1_DESC">Description of policy1. -With a newline.</message> - <message name="IDS_POLICY_POLICY2_DESC">Description of policy2. -With a newline.</message> - <message name="IDS_POLICY_POLICY1_CAPTION">Caption of policy1.</message> - <message name="IDS_POLICY_POLICY2_CAPTION">Caption of policy2.</message> - <message name="IDS_POLICY_WIN_SUPPORTED_WINXPSP2">At least Windows 3.16</message> - </messages> - ''') + 'messages': { + 'win_supported_winxpsp2': { + 'text': 'At least Windows 3.16', 'desc': 'blah' + } + } + }''') output = self.GetOutput(grd, 'fr', {'_chromium' : '1'}, 'adm', 'en') expected_output = '''CLASS MACHINE CATEGORY !!chromium diff --git a/tools/grit/grit/format/policy_templates/writers/adml_writer.py b/tools/grit/grit/format/policy_templates/writers/adml_writer.py index a518a2fb..d2f476f 100644 --- a/tools/grit/grit/format/policy_templates/writers/adml_writer.py +++ b/tools/grit/grit/format/policy_templates/writers/adml_writer.py @@ -6,12 +6,12 @@ from xml.dom import minidom from grit.format.policy_templates.writers import xml_formatted_writer -def GetWriter(config, messages): +def GetWriter(config): '''Factory method for instanciating the ADMLWriter. Every Writer needs a GetWriter method because the TemplateFormatter uses this method to instantiate a Writer. ''' - return ADMLWriter(['win'], config, messages) + return ADMLWriter(['win'], config) class ADMLWriter(xml_formatted_writer.XMLFormattedWriter): @@ -132,7 +132,7 @@ class ADMLWriter(xml_formatted_writer.XMLFormattedWriter): the ADMX file but not related to any specific Policy-Group or Policy. ''' self._AddString(string_table_elem, self.config['win_supported_os'], - self.messages[self.config['win_supported_os_msg']]) + self.messages['win_supported_winxpsp2']['text']) if build == 'chrome': self._AddString(string_table_elem, self.config['win_category_path'][0], 'Google') diff --git a/tools/grit/grit/format/policy_templates/writers/adml_writer_unittest.py b/tools/grit/grit/format/policy_templates/writers/adml_writer_unittest.py index 0ac74a6..9231f68 100644 --- a/tools/grit/grit/format/policy_templates/writers/adml_writer_unittest.py +++ b/tools/grit/grit/format/policy_templates/writers/adml_writer_unittest.py @@ -25,13 +25,14 @@ class AdmlWriterTest(xml_writer_base_unittest.XmlWriterBaseTest): config = { 'build': 'test', 'win_supported_os': 'SUPPORTED_TESTOS', - 'win_supported_os_msg': 'IDS_POLICY_WIN_SUPPORTED_WINXPSP2', } - # Grid messages - messages = { - 'IDS_POLICY_WIN_SUPPORTED_WINXPSP2': 'Supported on Test OS or higher' + self.writer = adml_writer.GetWriter(config) + self.writer.messages = { + 'win_supported_winxpsp2': { + 'text': 'Supported on Test OS or higher', + 'desc': 'blah' + } } - self.writer = adml_writer.GetWriter(config, messages) self.writer.Init() def _InitWriterForAddingPolicyGroups(self, writer): diff --git a/tools/grit/grit/format/policy_templates/writers/admx_writer.py b/tools/grit/grit/format/policy_templates/writers/admx_writer.py index 8737f54..06863d8 100644 --- a/tools/grit/grit/format/policy_templates/writers/admx_writer.py +++ b/tools/grit/grit/format/policy_templates/writers/admx_writer.py @@ -6,12 +6,12 @@ from xml.dom import minidom from grit.format.policy_templates.writers import xml_formatted_writer -def GetWriter(config, messages): +def GetWriter(config): '''Factory method for instanciating the ADMXWriter. Every Writer needs a GetWriter method because the TemplateFormatter uses this method to instantiate a Writer. ''' - return ADMXWriter(['win'], config, messages) + return ADMXWriter(['win'], config) class ADMXWriter(xml_formatted_writer.XMLFormattedWriter): diff --git a/tools/grit/grit/format/policy_templates/writers/admx_writer_unittest.py b/tools/grit/grit/format/policy_templates/writers/admx_writer_unittest.py index b3cba29..1e82bae 100644 --- a/tools/grit/grit/format/policy_templates/writers/admx_writer_unittest.py +++ b/tools/grit/grit/format/policy_templates/writers/admx_writer_unittest.py @@ -32,15 +32,12 @@ class AdmxWriterTest(xml_writer_base_unittest.XmlWriterBaseTest): config = { 'win_group_policy_class': 'TestClass', 'win_supported_os': 'SUPPORTED_TESTOS', - 'win_supported_os_msg': 'IDS_POLICY_WIN_SUPPORTED_WINXPSP2', 'win_reg_key_name': 'Software\\Policies\\Test', 'win_category_path': ['test_category'], 'admx_namespace': 'ADMXWriter.Test.Namespace', 'admx_prefix': 'test_prefix' } - # Grit messages. - messages = {} - self.writer = admx_writer.GetWriter(config, messages) + self.writer = admx_writer.GetWriter(config) self.writer.Init() def _GetPoliciesElement(self, doc): diff --git a/tools/grit/grit/format/policy_templates/writers/doc_writer.py b/tools/grit/grit/format/policy_templates/writers/doc_writer.py index 80e7880..1d3b7ef 100644 --- a/tools/grit/grit/format/policy_templates/writers/doc_writer.py +++ b/tools/grit/grit/format/policy_templates/writers/doc_writer.py @@ -9,12 +9,12 @@ from xml.dom import minidom from grit.format.policy_templates.writers import xml_formatted_writer -def GetWriter(config, messages): +def GetWriter(config): '''Factory method for creating DocWriter objects. See the constructor of TemplateWriter for description of arguments. ''' - return DocWriter(['*'], config, messages) + return DocWriter(['*'], config) class DocWriter(xml_formatted_writer.XMLFormattedWriter): @@ -41,7 +41,7 @@ class DocWriter(xml_formatted_writer.XMLFormattedWriter): Returns: The localized message. ''' - return self.messages['IDS_POLICY_DOC_' + msg_id.upper()] + return self.messages['doc_' + msg_id]['text'] def _MapListToString(self, item_map, items): '''Creates a comma-separated list. diff --git a/tools/grit/grit/format/policy_templates/writers/doc_writer_unittest.py b/tools/grit/grit/format/policy_templates/writers/doc_writer_unittest.py index 9aafd11..56f02f3 100644 --- a/tools/grit/grit/format/policy_templates/writers/doc_writer_unittest.py +++ b/tools/grit/grit/format/policy_templates/writers/doc_writer_unittest.py @@ -31,29 +31,6 @@ class MockMessageDictionary: # Dictionary of messages. msg_dict = {} - def __getitem__(self, msg_id): - '''Returns a message for an identifier. The identifier is transformed - back from IDS_POLICY_DOC... style names to the keys that the writer used. - If it is then key in self.msg_dict, then the message comes from there. - Otherwise the returned message is just the transformed version of the - identifier. This makes things more simple for testing. - - Args: - msg_id: The message identifier. - - Returns: - The mock message for msg_id. - ''' - # Do some trickery to get the original message id issued in DocWriter. - expected_prefix = 'IDS_POLICY_DOC_' - assert msg_id.startswith(expected_prefix) - original_msg_id = msg_id[len(expected_prefix):].lower() - - if original_msg_id in self.msg_dict: - return self.msg_dict[original_msg_id] - return '_test_' + original_msg_id - - class DocWriterUnittest(writer_unittest_common.WriterUnittestCommon): '''Unit tests for DocWriter.''' @@ -65,8 +42,29 @@ class DocWriterUnittest(writer_unittest_common.WriterUnittestCommon): 'frame_name': 'Chrome Frame', 'os_name': 'Chrome OS', 'win_reg_key_name': 'MockKey', + }) + self.writer.messages = { + 'doc_back_to_top': {'text': '_test_back_to_top'}, + 'doc_data_type': {'text': '_test_data_type'}, + 'doc_description': {'text': '_test_description'}, + 'doc_description_column_title': { + 'text': '_test_description_column_title' }, - messages=MockMessageDictionary()) + 'doc_example_value': {'text': '_test_example_value'}, + 'doc_feature_dynamic_refresh': {'text': '_test_feature_dynamic_refresh'}, + 'doc_intro': {'text': '_test_intro'}, + 'doc_mac_linux_pref_name': {'text': '_test_mac_linux_pref_name'}, + 'doc_note': {'text': '_test_note'}, + 'doc_name_column_title': {'text': '_test_name_column_title'}, + 'doc_not_supported': {'text': '_test_not_supported'}, + 'doc_since_version': {'text': '_test_since_version'}, + 'doc_supported': {'text': '_test_supported'}, + 'doc_supported_features': {'text': '_test_supported_features'}, + 'doc_supported_on': {'text': '_test_supported_on'}, + 'doc_win_reg_loc': {'text': '_test_win_reg_loc'}, + + 'doc_bla': {'text': '_test_bla'}, + } self.writer.Init() # It is not worth testing the exact content of style attributes. @@ -108,7 +106,7 @@ class DocWriterUnittest(writer_unittest_common.WriterUnittestCommon): def testGetLocalizedMessage(self): # Test if localized messages are retrieved correctly. self.writer.messages = { - 'IDS_POLICY_DOC_HELLO_WORLD': 'hello, vilag!' + 'doc_hello_world': {'text': 'hello, vilag!'} } self.assertEquals( self.writer._GetLocalizedMessage('hello_world'), @@ -358,7 +356,7 @@ See <a href="http://policy-explanation.example.com">http://policy-explanation.ex 'example_value': False } } - self.writer.messages.msg_dict['since_version'] = '...$6...' + self.writer.messages['doc_since_version'] = {'text': '...$6...'} self.writer._AddPolicyDetails(self.doc_root, policy) self.assertEquals( self.doc_root.toxml(), @@ -388,7 +386,7 @@ See <a href="http://policy-explanation.example.com">http://policy-explanation.ex 'problem_href': 'http://www.example.com/5' } } - self.writer.messages.msg_dict['note'] = '...$6...' + self.writer.messages['doc_note'] = {'text': '...$6...'} self.writer._AddPolicyNote(self.doc_root, policy) self.assertEquals( self.doc_root.toxml(), @@ -447,7 +445,7 @@ See <a href="http://policy-explanation.example.com">http://policy-explanation.ex 'example_value': False } } - self.writer.messages.msg_dict['since_version'] = '..$6..' + self.writer.messages['doc_since_version'] = {'text': '..$6..'} self.writer._AddPolicySection(self.doc_root, policy) self.assertEquals( self.doc_root.toxml(), diff --git a/tools/grit/grit/format/policy_templates/writers/json_writer.py b/tools/grit/grit/format/policy_templates/writers/json_writer.py index 7eda7fa..a754305 100644 --- a/tools/grit/grit/format/policy_templates/writers/json_writer.py +++ b/tools/grit/grit/format/policy_templates/writers/json_writer.py @@ -7,12 +7,12 @@ from xml.dom import minidom from grit.format.policy_templates.writers import template_writer -def GetWriter(config, messages): +def GetWriter(config): '''Factory method for creating JsonWriter objects. See the constructor of TemplateWriter for description of arguments. ''' - return JsonWriter(['linux'], config, messages) + return JsonWriter(['linux'], config) class JsonWriter(template_writer.TemplateWriter): diff --git a/tools/grit/grit/format/policy_templates/writers/json_writer_unittest.py b/tools/grit/grit/format/policy_templates/writers/json_writer_unittest.py index 17e4272..0d86634 100644 --- a/tools/grit/grit/format/policy_templates/writers/json_writer_unittest.py +++ b/tools/grit/grit/format/policy_templates/writers/json_writer_unittest.py @@ -39,8 +39,9 @@ class JsonWriterUnittest(writer_unittest_common.WriterUnittestCommon): '{' ' "policy_definitions": [],' ' "placeholders": [],' - '}', '<messages></messages>') - output = self.GetOutput(grd, 'fr', {'_chromium': '1', }, 'json', 'en') + ' "messages": {},' + '}') + output = self.GetOutput(grd, 'fr', {'_chromium': '1',}, 'json', 'en') expected_output = '{\n}' self.CompareOutputs(output, expected_output) @@ -52,6 +53,8 @@ class JsonWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' {' ' "name": "MainPolicy",' ' "type": "main",' + ' "caption": "",' + ' "desc": "",' ' "supported_on": ["chrome.linux:8-"],' ' "annotations": {' ' "example_value": True' @@ -59,11 +62,8 @@ class JsonWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' },' ' ],' ' "placeholders": [],' - '}', - '<messages>' - ' <message name="IDS_POLICY_MAINPOLICY_CAPTION"></message>' - ' <message name="IDS_POLICY_MAINPOLICY_DESC"></message>' - '</messages>') + ' "messages": {},' + '}') output = self.GetOutput(grd, 'fr', {'_google_chrome' : '1'}, 'json', 'en') expected_output = ( '{\n' @@ -79,6 +79,8 @@ class JsonWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' {' ' "name": "StringPolicy",' ' "type": "string",' + ' "caption": "",' + ' "desc": "",' ' "supported_on": ["chrome.linux:8-"],' ' "annotations": {' ' "example_value": "hello, world!"' @@ -86,11 +88,8 @@ class JsonWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' },' ' ],' ' "placeholders": [],' - '}', - '<messages>' - ' <message name="IDS_POLICY_STRINGPOLICY_CAPTION"></message>' - ' <message name="IDS_POLICY_STRINGPOLICY_DESC"></message>' - '</messages>') + ' "messages": {},' + '}') output = self.GetOutput(grd, 'fr', {'_chromium' : '1'}, 'json', 'en') expected_output = ( '{\n' @@ -106,6 +105,8 @@ class JsonWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' {' ' "name": "IntPolicy",' ' "type": "int",' + ' "caption": "",' + ' "desc": "",' ' "supported_on": ["chrome.linux:8-"],' ' "annotations": {' ' "example_value": 15' @@ -113,11 +114,8 @@ class JsonWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' },' ' ],' ' "placeholders": [],' - '}', - '<messages>' - ' <message name="IDS_POLICY_INTPOLICY_CAPTION"></message>' - ' <message name="IDS_POLICY_INTPOLICY_DESC"></message>' - '</messages>') + ' "messages": {},' + '}') output = self.GetOutput(grd, 'fr', {'_chromium' : '1'}, 'json', 'en') expected_output = ( '{\n' @@ -133,9 +131,11 @@ class JsonWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' {' ' "name": "EnumPolicy",' ' "type": "int-enum",' + ' "caption": "",' + ' "desc": "",' ' "items": [' - ' {"name": "ProxyServerDisabled", "value": 0},' - ' {"name": "ProxyServerAutoDetect", "value": 1},' + ' {"name": "ProxyServerDisabled", "value": 0, "caption": ""},' + ' {"name": "ProxyServerAutoDetect", "value": 1, "caption": ""},' ' ],' ' "supported_on": ["chrome.linux:8-"],' ' "annotations": {' @@ -144,15 +144,8 @@ class JsonWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' },' ' ],' ' "placeholders": [],' - '}', - '<messages>' - ' <message name="IDS_POLICY_ENUMPOLICY_CAPTION"></message>' - ' <message name="IDS_POLICY_ENUMPOLICY_DESC"></message>' - ' <message name="IDS_POLICY_ENUM_PROXYSERVERDISABLED_CAPTION">' - ' </message>' - ' <message name="IDS_POLICY_ENUM_PROXYSERVERAUTODETECT_CAPTION">' - ' </message>' - '</messages>') + ' "messages": {},' + '}') output = self.GetOutput(grd, 'fr', {'_google_chrome': '1'}, 'json', 'en') expected_output = ( '{\n' @@ -168,9 +161,13 @@ class JsonWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' {' ' "name": "EnumPolicy",' ' "type": "string-enum",' + ' "caption": "",' + ' "desc": "",' ' "items": [' - ' {"name": "ProxyServerDisabled", "value": "one"},' - ' {"name": "ProxyServerAutoDetect", "value": "two"},' + ' {"name": "ProxyServerDisabled", "value": "one",' + ' "caption": ""},' + ' {"name": "ProxyServerAutoDetect", "value": "two",' + ' "caption": ""},' ' ],' ' "supported_on": ["chrome.linux:8-"],' ' "annotations": {' @@ -179,15 +176,8 @@ class JsonWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' },' ' ],' ' "placeholders": [],' - '}', - '<messages>' - ' <message name="IDS_POLICY_ENUMPOLICY_CAPTION"></message>' - ' <message name="IDS_POLICY_ENUMPOLICY_DESC"></message>' - ' <message name="IDS_POLICY_ENUM_PROXYSERVERDISABLED_CAPTION">' - ' </message>' - ' <message name="IDS_POLICY_ENUM_PROXYSERVERAUTODETECT_CAPTION">' - ' </message>' - '</messages>') + ' "messages": {},' + '}') output = self.GetOutput(grd, 'fr', {'_google_chrome': '1'}, 'json', 'en') expected_output = ( '{\n' @@ -203,6 +193,8 @@ class JsonWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' {' ' "name": "ListPolicy",' ' "type": "list",' + ' "caption": "",' + ' "desc": "",' ' "supported_on": ["chrome.linux:8-"],' ' "annotations": {' ' "example_value": ["foo", "bar"]' @@ -210,12 +202,8 @@ class JsonWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' },' ' ],' ' "placeholders": [],' - '}', - '<messages>' - ' <message name="IDS_POLICY_LISTPOLICY_DESC"></message>' - ' <message name="IDS_POLICY_LISTPOLICY_CAPTION"></message>' - ' <message name="IDS_POLICY_LISTPOLICY_LABEL"></message>' - '</messages>') + ' "messages": {},' + '}') output = self.GetOutput(grd, 'fr', {'_chromium' : '1'}, 'json', 'en') expected_output = ( '{\n' @@ -232,6 +220,8 @@ class JsonWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' {' ' "name": "NonLinuxPolicy",' ' "type": "list",' + ' "caption": "",' + ' "desc": "",' ' "supported_on": ["chrome.mac:8-"],' ' "annotations": {' ' "example_value": ["a"]' @@ -239,11 +229,8 @@ class JsonWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' },' ' ],' ' "placeholders": [],' - '}', - '<messages>' - ' <message name="IDS_POLICY_NONLINUXPOLICY_CAPTION"></message>' - ' <message name="IDS_POLICY_NONLINUXPOLICY_DESC"></message>' - '</messages>') + ' "messages": {},' + '}') output = self.GetOutput(grd, 'fr', {'_chromium' : '1'}, 'json', 'en') expected_output = '{\n}' self.CompareOutputs(output, expected_output) @@ -256,9 +243,13 @@ class JsonWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' {' ' "name": "Group1",' ' "type": "group",' + ' "caption": "",' + ' "desc": "",' ' "policies": [{' ' "name": "Policy1",' ' "type": "list",' + ' "caption": "",' + ' "desc": "",' ' "supported_on": ["chrome.linux:8-"],' ' "annotations": {' ' "example_value": ["a", "b"]' @@ -266,6 +257,8 @@ class JsonWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' },{' ' "name": "Policy2",' ' "type": "string",' + ' "caption": "",' + ' "desc": "",' ' "supported_on": ["chrome.linux:8-"],' ' "annotations": {' ' "example_value": "c"' @@ -274,15 +267,8 @@ class JsonWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' },' ' ],' ' "placeholders": [],' - '}', - '<messages>' - ' <message name="IDS_POLICY_GROUP1_CAPTION"></message>' - ' <message name="IDS_POLICY_GROUP1_DESC"></message>' - ' <message name="IDS_POLICY_POLICY1_DESC"></message>' - ' <message name="IDS_POLICY_POLICY2_DESC"></message>' - ' <message name="IDS_POLICY_POLICY1_CAPTION"></message>' - ' <message name="IDS_POLICY_POLICY2_CAPTION"></message>' - '</messages>') + ' "messages": {},' + '}') output = self.GetOutput(grd, 'fr', {'_chromium' : '1'}, 'json', 'en') expected_output = ( '{\n' diff --git a/tools/grit/grit/format/policy_templates/writers/plist_strings_writer.py b/tools/grit/grit/format/policy_templates/writers/plist_strings_writer.py index bb1a634..082e9f8 100644 --- a/tools/grit/grit/format/policy_templates/writers/plist_strings_writer.py +++ b/tools/grit/grit/format/policy_templates/writers/plist_strings_writer.py @@ -7,12 +7,12 @@ from grit.format.policy_templates.writers import plist_helper from grit.format.policy_templates.writers import template_writer -def GetWriter(config, messages): +def GetWriter(config): '''Factory method for creating PListStringsWriter objects. See the constructor of TemplateWriter for description of arguments. ''' - return PListStringsWriter(['mac'], config, messages) + return PListStringsWriter(['mac'], config) class PListStringsWriter(template_writer.TemplateWriter): @@ -62,7 +62,7 @@ class PListStringsWriter(template_writer.TemplateWriter): self._AddToStringTable( app_name, self.config['app_name'], - self.messages['IDS_POLICY_MAC_CHROME_PREFERENCES']) + self.messages['mac_chrome_preferences']['text']) def Init(self): # A buffer for the lines of the string table being generated. diff --git a/tools/grit/grit/format/policy_templates/writers/plist_strings_writer_unittest.py b/tools/grit/grit/format/policy_templates/writers/plist_strings_writer_unittest.py index 0c55da4..15db925 100644 --- a/tools/grit/grit/format/policy_templates/writers/plist_strings_writer_unittest.py +++ b/tools/grit/grit/format/policy_templates/writers/plist_strings_writer_unittest.py @@ -1,5 +1,5 @@ #!/usr/bin/python2.4 -# Copyright (c) 2010 The Chromium Authors. All rights reserved. +# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. @@ -30,11 +30,13 @@ class PListStringsWriterUnittest(writer_unittest_common.WriterUnittestCommon): { 'policy_definitions': [], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_MAC_CHROME_PREFERENCES">$1 preferen"ces</message> - </messages> - ''') + 'messages': { + 'mac_chrome_preferences': { + 'text': '$1 preferen"ces', + 'desc': 'blah' + } + } + }''') output = self.GetOutput( grd, 'fr', @@ -54,23 +56,25 @@ class PListStringsWriterUnittest(writer_unittest_common.WriterUnittestCommon): { 'name': 'MainGroup', 'type': 'group', + 'caption': 'Caption of main.', + 'desc': 'Description of main.', 'policies': [{ 'name': 'MainPolicy', 'type': 'main', 'supported_on': ['chrome.mac:8-'], + 'caption': 'Caption of main policy.', + 'desc': 'Description of main policy.', }], }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_MAINGROUP_CAPTION">Caption of main.</message> - <message name="IDS_POLICY_MAINGROUP_DESC">Title of main.</message> - <message name="IDS_POLICY_MAINPOLICY_CAPTION">Caption of main policy.</message> - <message name="IDS_POLICY_MAINPOLICY_DESC">Title of main policy.</message> - <message name="IDS_POLICY_MAC_CHROME_PREFERENCES">Preferences of $1</message> - </messages> - ''') + 'messages': { + 'mac_chrome_preferences': { + 'text': 'Preferences of $1', + 'desc': 'blah' + } + } + }''') output = self.GetOutput( grd, 'fr', @@ -81,7 +85,7 @@ class PListStringsWriterUnittest(writer_unittest_common.WriterUnittestCommon): 'Google_Chrome.pfm_title = "Google Chrome";\n' 'Google_Chrome.pfm_description = "Preferences of Google Chrome";\n' 'MainPolicy.pfm_title = "Caption of main policy.";\n' - 'MainPolicy.pfm_description = "Title of main policy.";') + 'MainPolicy.pfm_description = "Description of main policy.";') self.assertEquals(output.strip(), expected_output.strip()) def testStringPolicy(self): @@ -93,25 +97,27 @@ class PListStringsWriterUnittest(writer_unittest_common.WriterUnittestCommon): { 'name': 'StringGroup', 'type': 'group', + 'caption': 'Caption of group.', + 'desc': """Description of group. +With a newline.""", 'policies': [{ 'name': 'StringPolicy', 'type': 'string', + 'caption': 'Caption of policy.', + 'desc': """Description of policy. +With a newline.""", 'supported_on': ['chrome.mac:8-'], }], }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_STRINGGROUP_CAPTION">Caption of group.</message> - <message name="IDS_POLICY_STRINGGROUP_DESC">Description of group. -With a newline.</message> - <message name="IDS_POLICY_STRINGPOLICY_CAPTION">Caption of policy.</message> - <message name="IDS_POLICY_STRINGPOLICY_DESC">Description of policy. -With a newline.</message> - <message name="IDS_POLICY_MAC_CHROME_PREFERENCES">Preferences Of $1</message> - </messages> - ''') + 'messages': { + 'mac_chrome_preferences': { + 'text': 'Preferences of $1', + 'desc': 'blah' + } + } + }''') output = self.GetOutput( grd, 'fr', @@ -120,7 +126,7 @@ With a newline.</message> 'en') expected_output = ( 'Chromium.pfm_title = "Chromium";\n' - 'Chromium.pfm_description = "Preferences Of Chromium";\n' + 'Chromium.pfm_description = "Preferences of Chromium";\n' 'StringPolicy.pfm_title = "Caption of policy.";\n' 'StringPolicy.pfm_description = ' '"Description of policy.\\nWith a newline.";') @@ -134,29 +140,37 @@ With a newline.</message> { 'name': 'EnumGroup', 'type': 'group', + 'desc': '', + 'caption': '', 'policies': [{ 'name': 'EnumPolicy', 'type': 'int-enum', + 'desc': 'Description of policy.', + 'caption': 'Caption of policy.', 'items': [ - {'name': 'ProxyServerDisabled', 'value': 0}, - {'name': 'ProxyServerAutoDetect', 'value': 1}, + { + 'name': 'ProxyServerDisabled', + 'value': 0, + 'caption': 'Option1' + }, + { + 'name': 'ProxyServerAutoDetect', + 'value': 1, + 'caption': 'Option2' + }, ], 'supported_on': ['chrome.mac:8-'], }], }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_ENUMGROUP_CAPTION">Caption of group.</message> - <message name="IDS_POLICY_ENUMGROUP_DESC">Description of group.</message> - <message name="IDS_POLICY_ENUMPOLICY_CAPTION">Caption of policy.</message> - <message name="IDS_POLICY_ENUMPOLICY_DESC">Description of policy.</message> - <message name="IDS_POLICY_ENUM_PROXYSERVERDISABLED_CAPTION">Option1</message> - <message name="IDS_POLICY_ENUM_PROXYSERVERAUTODETECT_CAPTION">Option2</message> - <message name="IDS_POLICY_MAC_CHROME_PREFERENCES">$1 preferences</message> - </messages> - ''') + 'messages': { + 'mac_chrome_preferences': { + 'text': '$1 preferences', + 'desc': 'blah' + } + } + }''') output = self.GetOutput( grd, 'fr', @@ -180,29 +194,37 @@ With a newline.</message> { 'name': 'EnumGroup', 'type': 'group', + 'desc': '', + 'caption': '', 'policies': [{ 'name': 'EnumPolicy', 'type': 'string-enum', + 'desc': 'Description of policy.', + 'caption': 'Caption of policy.', 'items': [ - {'name': 'ProxyServerDisabled', 'value': "one"}, - {'name': 'ProxyServerAutoDetect', 'value': "two"}, + { + 'name': 'ProxyServerDisabled', + 'value': 'one', + 'caption': 'Option1' + }, + { + 'name': 'ProxyServerAutoDetect', + 'value': 'two', + 'caption': 'Option2' + }, ], 'supported_on': ['chrome.mac:8-'], }], }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_ENUMGROUP_CAPTION">Caption of group.</message> - <message name="IDS_POLICY_ENUMGROUP_DESC">Description of group.</message> - <message name="IDS_POLICY_ENUMPOLICY_CAPTION">Caption of policy.</message> - <message name="IDS_POLICY_ENUMPOLICY_DESC">Description of policy.</message> - <message name="IDS_POLICY_ENUM_PROXYSERVERDISABLED_CAPTION">Option1</message> - <message name="IDS_POLICY_ENUM_PROXYSERVERAUTODETECT_CAPTION">Option2</message> - <message name="IDS_POLICY_MAC_CHROME_PREFERENCES">$1 preferences</message> - </messages> - ''') + 'messages': { + 'mac_chrome_preferences': { + 'text': '$1 preferences', + 'desc': 'blah' + } + } + }''') output = self.GetOutput( grd, 'fr', @@ -227,23 +249,25 @@ With a newline.</message> { 'name': 'NonMacGroup', 'type': 'group', + 'caption': '', + 'desc': '', 'policies': [{ 'name': 'NonMacPolicy', 'type': 'string', + 'caption': '', + 'desc': '', 'supported_on': ['chrome_os:8-'], }], }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_NONMACGROUP_CAPTION">Caption of group.</message> - <message name="IDS_POLICY_NONMACGROUP_DESC">Description of group.</message> - <message name="IDS_POLICY_NONMACPOLICY_CAPTION">Caption of policy.</message> - <message name="IDS_POLICY_NONMACPOLICY_DESC">Description of policy.</message> - <message name="IDS_POLICY_MAC_CHROME_PREFERENCES">$1 preferences</message> - </messages> - ''') + 'messages': { + 'mac_chrome_preferences': { + 'text': '$1 preferences', + 'desc': 'blah' + } + } + }''') output = self.GetOutput( grd, 'fr', diff --git a/tools/grit/grit/format/policy_templates/writers/plist_writer.py b/tools/grit/grit/format/policy_templates/writers/plist_writer.py index 46b00b3..1dc4da0 100644 --- a/tools/grit/grit/format/policy_templates/writers/plist_writer.py +++ b/tools/grit/grit/format/policy_templates/writers/plist_writer.py @@ -8,12 +8,12 @@ from grit.format.policy_templates.writers import plist_helper from grit.format.policy_templates.writers import xml_formatted_writer -def GetWriter(config, messages): +def GetWriter(config): '''Factory method for creating PListWriter objects. See the constructor of TemplateWriter for description of arguments. ''' - return PListWriter(['mac'], config, messages) + return PListWriter(['mac'], config) class PListWriter(xml_formatted_writer.XMLFormattedWriter): diff --git a/tools/grit/grit/format/policy_templates/writers/plist_writer_unittest.py b/tools/grit/grit/format/policy_templates/writers/plist_writer_unittest.py index 10d1a26..4f51f3c 100644 --- a/tools/grit/grit/format/policy_templates/writers/plist_writer_unittest.py +++ b/tools/grit/grit/format/policy_templates/writers/plist_writer_unittest.py @@ -65,7 +65,8 @@ class PListWriterUnittest(writer_unittest_common.WriterUnittestCommon): { 'policy_definitions': [], 'placeholders': [], - }''', '''<messages />''') + 'messages': {}, + }''') output = self.GetOutput( grd, @@ -88,19 +89,17 @@ class PListWriterUnittest(writer_unittest_common.WriterUnittestCommon): 'policies': [{ 'name': 'MainPolicy', 'type': 'main', + 'desc': '', + 'caption': '', 'supported_on': ['chrome.mac:8-'], }], + 'desc': '', + 'caption': '', }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_MAINGROUP_CAPTION">This is not tested here.</message> - <message name="IDS_POLICY_MAINGROUP_DESC">This is not tested here.</message> - <message name="IDS_POLICY_MAINPOLICY_CAPTION">This is not tested here.</message> - <message name="IDS_POLICY_MAINPOLICY_DESC">This is not tested here.</message> - </messages> - ''') + 'messages': {} + }''') output = self.GetOutput( grd, 'fr', @@ -134,22 +133,20 @@ class PListWriterUnittest(writer_unittest_common.WriterUnittestCommon): { 'name': 'StringGroup', 'type': 'group', + 'desc': '', + 'caption': '', 'policies': [{ 'name': 'StringPolicy', 'type': 'string', 'supported_on': ['chrome.mac:8-'], + 'desc': '', + 'caption': '', }], }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_STRINGGROUP_CAPTION">This is not tested here.</message> - <message name="IDS_POLICY_STRINGGROUP_DESC">This is not tested here.</message> - <message name="IDS_POLICY_STRINGPOLICY_CAPTION">This is not tested here.</message> - <message name="IDS_POLICY_STRINGPOLICY_DESC">This is not tested here.</message> - </messages> - ''') + 'messages': {}, + }''') output = self.GetOutput( grd, 'fr', @@ -183,22 +180,20 @@ class PListWriterUnittest(writer_unittest_common.WriterUnittestCommon): { 'name': 'IntGroup', 'type': 'group', + 'caption': '', + 'desc': '', 'policies': [{ 'name': 'IntPolicy', 'type': 'int', + 'caption': '', + 'desc': '', 'supported_on': ['chrome.mac:8-'], }], }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_INTGROUP_CAPTION">This is not tested here.</message> - <message name="IDS_POLICY_INTGROUP_DESC">This is not tested here.</message> - <message name="IDS_POLICY_INTPOLICY_CAPTION">This is not tested here.</message> - <message name="IDS_POLICY_INTPOLICY_DESC">This is not tested here.</message> - </messages> - ''') + 'messages': {}, + }''') output = self.GetOutput( grd, 'fr', @@ -232,28 +227,24 @@ class PListWriterUnittest(writer_unittest_common.WriterUnittestCommon): { 'name': 'EnumGroup', 'type': 'group', + 'caption': '', + 'desc': '', 'policies': [{ 'name': 'EnumPolicy', 'type': 'int-enum', + 'desc': '', + 'caption': '', 'items': [ - {'name': 'ProxyServerDisabled', 'value': 0}, - {'name': 'ProxyServerAutoDetect', 'value': 1}, + {'name': 'ProxyServerDisabled', 'value': 0, 'caption': ''}, + {'name': 'ProxyServerAutoDetect', 'value': 1, 'caption': ''}, ], 'supported_on': ['chrome.mac:8-'], }], }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_ENUMGROUP_CAPTION">This is not tested here.</message> - <message name="IDS_POLICY_ENUMGROUP_DESC">This is not tested here.</message> - <message name="IDS_POLICY_ENUMPOLICY_CAPTION">This is not tested here.</message> - <message name="IDS_POLICY_ENUMPOLICY_DESC">This is not tested here.</message> - <message name="IDS_POLICY_ENUM_PROXYSERVERDISABLED_CAPTION">This is not tested here.</message> - <message name="IDS_POLICY_ENUM_PROXYSERVERAUTODETECT_CAPTION">This is not tested here.</message> - </messages> - ''') + 'messages': {}, + }''') output = self.GetOutput( grd, 'fr', @@ -292,28 +283,24 @@ class PListWriterUnittest(writer_unittest_common.WriterUnittestCommon): { 'name': 'EnumGroup', 'type': 'group', + 'caption': '', + 'desc': '', 'policies': [{ 'name': 'EnumPolicy', 'type': 'string-enum', + 'desc': '', + 'caption': '', 'items': [ - {'name': 'ProxyServerDisabled', 'value': 'one'}, - {'name': 'ProxyServerAutoDetect', 'value': 'two'}, + {'name': 'ProxyServerDisabled', 'value': 'one', 'caption': ''}, + {'name': 'ProxyServerAutoDetect', 'value': 'two', 'caption': ''}, ], 'supported_on': ['chrome.mac:8-'], }], }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_ENUMGROUP_CAPTION">This is not tested here.</message> - <message name="IDS_POLICY_ENUMGROUP_DESC">This is not tested here.</message> - <message name="IDS_POLICY_ENUMPOLICY_CAPTION">This is not tested here.</message> - <message name="IDS_POLICY_ENUMPOLICY_DESC">This is not tested here.</message> - <message name="IDS_POLICY_ENUM_PROXYSERVERDISABLED_CAPTION">This is not tested here.</message> - <message name="IDS_POLICY_ENUM_PROXYSERVERAUTODETECT_CAPTION">This is not tested here.</message> - </messages> - ''') + 'messages': {}, + }''') output = self.GetOutput( grd, 'fr', @@ -353,22 +340,20 @@ class PListWriterUnittest(writer_unittest_common.WriterUnittestCommon): { 'name': 'NonMacGroup', 'type': 'group', + 'caption': '', + 'desc': '', 'policies': [{ 'name': 'NonMacPolicy', 'type': 'string', 'supported_on': ['chrome.linux:8-', 'chrome.win:7-'], + 'caption': '', + 'desc': '', }], }, ], 'placeholders': [], - }''', ''' - <messages> - <message name="IDS_POLICY_NONMACGROUP_CAPTION">This is not tested here. (1)</message> - <message name="IDS_POLICY_NONMACGROUP_DESC">This is not tested here. (2)</message> - <message name="IDS_POLICY_NONMACPOLICY_CAPTION">This is not tested here. (3)</message> - <message name="IDS_POLICY_NONMACPOLICY_DESC">This is not tested here. (4)</message> - </messages> - ''') + 'messages': {}, + }''') output = self.GetOutput( grd, 'fr', diff --git a/tools/grit/grit/format/policy_templates/writers/reg_writer.py b/tools/grit/grit/format/policy_templates/writers/reg_writer.py index 6032c48..4ff5508 100644 --- a/tools/grit/grit/format/policy_templates/writers/reg_writer.py +++ b/tools/grit/grit/format/policy_templates/writers/reg_writer.py @@ -7,12 +7,12 @@ from xml.dom import minidom from grit.format.policy_templates.writers import template_writer -def GetWriter(config, messages): +def GetWriter(config): '''Factory method for creating RegWriter objects. See the constructor of TemplateWriter for description of arguments. ''' - return RegWriter(['win'], config, messages) + return RegWriter(['win'], config) class RegWriter(template_writer.TemplateWriter): diff --git a/tools/grit/grit/format/policy_templates/writers/reg_writer_unittest.py b/tools/grit/grit/format/policy_templates/writers/reg_writer_unittest.py index 5d1851e..62d1ac7 100644 --- a/tools/grit/grit/format/policy_templates/writers/reg_writer_unittest.py +++ b/tools/grit/grit/format/policy_templates/writers/reg_writer_unittest.py @@ -42,8 +42,9 @@ class RegWriterUnittest(writer_unittest_common.WriterUnittestCommon): '{' ' "policy_definitions": [],' ' "placeholders": [],' - '}', '<messages></messages>') - output = self.GetOutput(grd, 'fr', {'_chromium': '1', }, 'reg', 'en') + ' "messages": {}' + '}') + output = self.GetOutput(grd, 'fr', {'_chromium': '1',}, 'reg', 'en') expected_output = 'Windows Registry Editor Version 5.00' self.CompareOutputs(output, expected_output) @@ -55,6 +56,8 @@ class RegWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' {' ' "name": "MainPolicy",' ' "type": "main",' + ' "caption": "",' + ' "desc": "",' ' "supported_on": ["chrome.win:8-"],' ' "annotations": {' ' "example_value": True' @@ -62,11 +65,8 @@ class RegWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' },' ' ],' ' "placeholders": [],' - '}', - '<messages>' - ' <message name="IDS_POLICY_MAINPOLICY_CAPTION"></message>' - ' <message name="IDS_POLICY_MAINPOLICY_DESC"></message>' - '</messages>') + ' "messages": {},' + '}') output = self.GetOutput(grd, 'fr', {'_google_chrome' : '1'}, 'reg', 'en') expected_output = self.NEWLINE.join([ 'Windows Registry Editor Version 5.00', @@ -83,6 +83,8 @@ class RegWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' {' ' "name": "StringPolicy",' ' "type": "string",' + ' "caption": "",' + ' "desc": "",' ' "supported_on": ["chrome.win:8-"],' ' "annotations": {' ' "example_value": "hello, world! \\\" \\\\"' @@ -90,11 +92,8 @@ class RegWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' },' ' ],' ' "placeholders": [],' - '}', - '<messages>' - ' <message name="IDS_POLICY_STRINGPOLICY_CAPTION"></message>' - ' <message name="IDS_POLICY_STRINGPOLICY_DESC"></message>' - '</messages>') + ' "messages": {},' + '}') output = self.GetOutput(grd, 'fr', {'_chromium' : '1'}, 'reg', 'en') expected_output = self.NEWLINE.join([ 'Windows Registry Editor Version 5.00', @@ -111,6 +110,8 @@ class RegWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' {' ' "name": "IntPolicy",' ' "type": "int",' + ' "caption": "",' + ' "desc": "",' ' "supported_on": ["chrome.win:8-"],' ' "annotations": {' ' "example_value": 26' @@ -118,11 +119,8 @@ class RegWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' },' ' ],' ' "placeholders": [],' - '}', - '<messages>' - ' <message name="IDS_POLICY_INTPOLICY_CAPTION"></message>' - ' <message name="IDS_POLICY_INTPOLICY_DESC"></message>' - '</messages>') + ' "messages": {},' + '}') output = self.GetOutput(grd, 'fr', {'_chromium' : '1'}, 'reg', 'en') expected_output = self.NEWLINE.join([ 'Windows Registry Editor Version 5.00', @@ -139,9 +137,11 @@ class RegWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' {' ' "name": "EnumPolicy",' ' "type": "int-enum",' + ' "caption": "",' + ' "desc": "",' ' "items": [' - ' {"name": "ProxyServerDisabled", "value": 0},' - ' {"name": "ProxyServerAutoDetect", "value": 1},' + ' {"name": "ProxyServerDisabled", "value": 0, "caption": ""},' + ' {"name": "ProxyServerAutoDetect", "value": 1, "caption": ""},' ' ],' ' "supported_on": ["chrome.win:8-"],' ' "annotations": {' @@ -150,15 +150,8 @@ class RegWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' },' ' ],' ' "placeholders": [],' - '}', - '<messages>' - ' <message name="IDS_POLICY_ENUMPOLICY_CAPTION"></message>' - ' <message name="IDS_POLICY_ENUMPOLICY_DESC"></message>' - ' <message name="IDS_POLICY_ENUM_PROXYSERVERDISABLED_CAPTION">' - ' </message>' - ' <message name="IDS_POLICY_ENUM_PROXYSERVERAUTODETECT_CAPTION">' - ' </message>' - '</messages>') + ' "messages": {},' + '}') output = self.GetOutput(grd, 'fr', {'_google_chrome': '1'}, 'reg', 'en') expected_output = self.NEWLINE.join([ 'Windows Registry Editor Version 5.00', @@ -175,9 +168,13 @@ class RegWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' {' ' "name": "EnumPolicy",' ' "type": "string-enum",' + ' "caption": "",' + ' "desc": "",' ' "items": [' - ' {"name": "ProxyServerDisabled", "value": "one"},' - ' {"name": "ProxyServerAutoDetect", "value": "two"},' + ' {"name": "ProxyServerDisabled", "value": "one",' + ' "caption": ""},' + ' {"name": "ProxyServerAutoDetect", "value": "two",' + ' "caption": ""},' ' ],' ' "supported_on": ["chrome.win:8-"],' ' "annotations": {' @@ -186,15 +183,8 @@ class RegWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' },' ' ],' ' "placeholders": [],' - '}', - '<messages>' - ' <message name="IDS_POLICY_ENUMPOLICY_CAPTION"></message>' - ' <message name="IDS_POLICY_ENUMPOLICY_DESC"></message>' - ' <message name="IDS_POLICY_ENUM_PROXYSERVERDISABLED_CAPTION">' - ' </message>' - ' <message name="IDS_POLICY_ENUM_PROXYSERVERAUTODETECT_CAPTION">' - ' </message>' - '</messages>') + ' "messages": {},' + '}') output = self.GetOutput(grd, 'fr', {'_google_chrome': '1'}, 'reg', 'en') expected_output = self.NEWLINE.join([ 'Windows Registry Editor Version 5.00', @@ -211,6 +201,8 @@ class RegWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' {' ' "name": "ListPolicy",' ' "type": "list",' + ' "caption": "",' + ' "desc": "",' ' "supported_on": ["chrome.linux:8-"],' ' "annotations": {' ' "example_value": ["foo", "bar"]' @@ -218,12 +210,8 @@ class RegWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' },' ' ],' ' "placeholders": [],' - '}', - '<messages>' - ' <message name="IDS_POLICY_LISTPOLICY_DESC"></message>' - ' <message name="IDS_POLICY_LISTPOLICY_CAPTION"></message>' - ' <message name="IDS_POLICY_LISTPOLICY_LABEL"></message>' - '</messages>') + ' "messages": {},' + '}') output = self.GetOutput(grd, 'fr', {'_chromium' : '1'}, 'reg', 'en') expected_output = self.NEWLINE.join([ 'Windows Registry Editor Version 5.00', @@ -241,6 +229,8 @@ class RegWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' {' ' "name": "NonWindowsPolicy",' ' "type": "list",' + ' "caption": "",' + ' "desc": "",' ' "supported_on": ["chrome.mac:8-"],' ' "annotations": {' ' "example_value": ["a"]' @@ -248,11 +238,8 @@ class RegWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' },' ' ],' ' "placeholders": [],' - '}', - '<messages>' - ' <message name="IDS_POLICY_NONWINDOWSPOLICY_CAPTION"></message>' - ' <message name="IDS_POLICY_NONWINDOWSPOLICY_DESC"></message>' - '</messages>') + ' "messages": {},' + '}') output = self.GetOutput(grd, 'fr', {'_chromium' : '1'}, 'reg', 'en') expected_output = self.NEWLINE.join([ 'Windows Registry Editor Version 5.00']) @@ -266,9 +253,13 @@ class RegWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' {' ' "name": "Group1",' ' "type": "group",' + ' "caption": "",' + ' "desc": "",' ' "policies": [{' ' "name": "Policy1",' ' "type": "list",' + ' "caption": "",' + ' "desc": "",' ' "supported_on": ["chrome.win:8-"],' ' "annotations": {' ' "example_value": ["a", "b"]' @@ -276,6 +267,8 @@ class RegWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' },{' ' "name": "Policy2",' ' "type": "string",' + ' "caption": "",' + ' "desc": "",' ' "supported_on": ["chrome.win:8-"],' ' "annotations": {' ' "example_value": "c"' @@ -284,15 +277,8 @@ class RegWriterUnittest(writer_unittest_common.WriterUnittestCommon): ' },' ' ],' ' "placeholders": [],' - '}', - '<messages>' - ' <message name="IDS_POLICY_GROUP1_CAPTION"></message>' - ' <message name="IDS_POLICY_GROUP1_DESC"></message>' - ' <message name="IDS_POLICY_POLICY1_DESC"></message>' - ' <message name="IDS_POLICY_POLICY2_DESC"></message>' - ' <message name="IDS_POLICY_POLICY1_CAPTION"></message>' - ' <message name="IDS_POLICY_POLICY2_CAPTION"></message>' - '</messages>') + ' "messages": {},' + '}') output = self.GetOutput(grd, 'fr', {'_chromium' : '1'}, 'reg', 'en') expected_output = self.NEWLINE.join([ 'Windows Registry Editor Version 5.00', diff --git a/tools/grit/grit/format/policy_templates/writers/template_writer.py b/tools/grit/grit/format/policy_templates/writers/template_writer.py index ecff851..539953a 100644 --- a/tools/grit/grit/format/policy_templates/writers/template_writer.py +++ b/tools/grit/grit/format/policy_templates/writers/template_writer.py @@ -11,7 +11,7 @@ class TemplateWriter(object): The methods of this class will be called by PolicyTemplateGenerator. ''' - def __init__(self, platforms, config, messages): + def __init__(self, platforms, config): '''Initializes a TemplateWriter object. Args: @@ -31,7 +31,6 @@ class TemplateWriter(object): ''' self.platforms = platforms self.config = config - self.messages = messages def IsDeprecatedPolicySupported(self, policy): '''Checks if the given deprecated policy is supported by the writer. @@ -104,10 +103,12 @@ class TemplateWriter(object): Returns: Generated output for the passed template definition. ''' + self.messages = template['messages'] self.Init() - template = self.PreprocessPolicies(template) + template['policy_definitions'] = \ + self.PreprocessPolicies(template['policy_definitions']) self.BeginTemplate() - for policy in template: + for policy in template['policy_definitions']: if policy['type'] == 'group': child_policies = self._GetPoliciesForWriter(policy) if child_policies: diff --git a/tools/grit/grit/format/policy_templates/writers/template_writer_unittest.py b/tools/grit/grit/format/policy_templates/writers/template_writer_unittest.py index 60ea55a..02d24a5 100644 --- a/tools/grit/grit/format/policy_templates/writers/template_writer_unittest.py +++ b/tools/grit/grit/format/policy_templates/writers/template_writer_unittest.py @@ -69,12 +69,12 @@ class TemplateWriterUnittests(unittest.TestCase): '''Unit tests for templater_writer.py.''' def testSortingGroupsFirst(self): - tw = template_writer.TemplateWriter(None, None, None) + tw = template_writer.TemplateWriter(None, None) sorted_list = tw.SortPoliciesGroupsFirst(POLICY_DEFS) self.assertEqual(sorted_list, GROUP_FIRST_SORTED_POLICY_DEFS) def testSortingIgnoreGroups(self): - tw = template_writer.TemplateWriter(None, None, None) + tw = template_writer.TemplateWriter(None, None) sorted_list = tw.FlattenGroupsAndSortPolicies(POLICY_DEFS) self.assertEqual(sorted_list, IGNORE_GROUPS_SORTED_POLICY_DEFS) diff --git a/tools/grit/grit/format/policy_templates/writers/writer_unittest_common.py b/tools/grit/grit/format/policy_templates/writers/writer_unittest_common.py index 0970772..9a10d12 100644 --- a/tools/grit/grit/format/policy_templates/writers/writer_unittest_common.py +++ b/tools/grit/grit/format/policy_templates/writers/writer_unittest_common.py @@ -1,4 +1,4 @@ -# Copyright (c) 2010 The Chromium Authors. All rights reserved. +# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. @@ -35,12 +35,11 @@ class DummyOutput(object): class WriterUnittestCommon(unittest.TestCase): '''Common class for unittesting writers.''' - def PrepareTest(self, policy_json, grd_messages_text): + def PrepareTest(self, policy_json): '''Prepares and parses a grit tree along with a data structure of policies. Args: policy_json: The policy data structure in JSON format. - grd_messages_text: The messages node of the grit tree in text form. ''' # First create a temporary file that contains the JSON policy list. tmp_file_name = 'test.json' @@ -50,16 +49,14 @@ class WriterUnittestCommon(unittest.TestCase): f.write(policy_json.strip()) f.close() # Then assemble the grit tree. - grd_begin_text = ''' + grd_text = ''' <grit base_dir="." latest_public_release="0" current_release="1" source_lang_id="en"> <release seq="1"> <structures> <structure name="IDD_POLICY_SOURCE_FILE" file="%s" type="policy_template_metafile" /> - </structures>''' % json_file_path - grd_end_text = ''' + </structures> </release> - </grit>''' - grd_text = grd_begin_text + grd_messages_text + grd_end_text + </grit>''' % json_file_path grd_string_io = StringIO.StringIO(grd_text) # Parse the grit tree and load the policies' JSON with a gatherer. grd = grd_reader.Parse(grd_string_io, dir=tmp_dir_name) diff --git a/tools/grit/grit/gather/muppet_strings.py b/tools/grit/grit/gather/muppet_strings.py index 545b129..119f851 100644 --- a/tools/grit/grit/gather/muppet_strings.py +++ b/tools/grit/grit/gather/muppet_strings.py @@ -121,6 +121,7 @@ class MuppetStrings(regexp.RegexpGatherer): def Parse(self): if (self.have_parsed_): return + self.have_parsed_ = True self._AddNontranslateableChunk(u'<strings>\n') stream = StringIO.StringIO(self.text_) handler = MuppetStringsContentHandler(self) diff --git a/tools/grit/grit/gather/policy_json.py b/tools/grit/grit/gather/policy_json.py new file mode 100644 index 0000000..cd7875f --- /dev/null +++ b/tools/grit/grit/gather/policy_json.py @@ -0,0 +1,263 @@ +#!/usr/bin/python2.4 +# Copyright (c) 2011 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +'''Support for "policy_templates.json" format used by the policy template +generator as a source for generating ADM,ADMX,etc files.''' + +import types +import pprint +import re + +from grit.gather import skeleton_gatherer +from grit import util +from grit import tclib +from xml.dom import minidom + + +class PolicyJson(skeleton_gatherer.SkeletonGatherer): + '''Collects and translates the following strings from policy_templates.json: + - captions,descriptions and labels of policies + - captions of enumeration items + - misc strings from the 'messages' section + Translatable strings may have untranslateable placeholders with the same + format that is used in .grd files. + ''' + + def __init__(self, text): + if util.IsExtraVerbose(): + print text + skeleton_gatherer.SkeletonGatherer.__init__(self) + self.text_ = text + + def _ParsePlaceholder(self, placeholder, msg): + '''Extracts a placeholder from a DOM node and adds it to a tclib Message. + + Args: + placeholder: A DOM node of the form: + <ph name="PLACEHOLDER_NAME">Placeholder text<ex>Example value</ex></ph> + msg: The placeholder is added to this message. + ''' + text = [] + example_text = [] + for node1 in placeholder.childNodes: + if (node1.nodeType == minidom.Node.TEXT_NODE): + text.append(node1.data) + elif (node1.nodeType == minidom.Node.ELEMENT_NODE and + node1.tagName == 'ex'): + for node2 in node1.childNodes: + example_text.append(node2.toxml()) + else: + raise Exception('Unexpected element inside a placeholder: ' + + node2.toxml()) + if example_text == []: + # In such cases the original text is okay for an example. + example_text = text + msg.AppendPlaceholder(tclib.Placeholder( + placeholder.attributes['name'].value, + ''.join(text).strip(), + ''.join(example_text).strip())) + + def _ParseMessage(self, string, desc): + '''Parses a given string and adds it to the output as a translatable chunk + with a given description. + + Args: + string: The message string to parse. + desc: The description of the message (for the translators). + ''' + msg = tclib.Message(description=desc) + xml = '<msg>' + string + '</msg>' + node = minidom.parseString(xml).childNodes[0] + for child in node.childNodes: + if child.nodeType == minidom.Node.TEXT_NODE: + msg.AppendText(child.data) + elif child.nodeType == minidom.Node.ELEMENT_NODE: + if child.tagName == 'ph': + self._ParsePlaceholder(child, msg) + else: + raise Exception("Not implemented.") + else: + raise Exception("Not implemented.") + self.skeleton_.append(self.uberclique.MakeClique(msg)) + + def _ParseNode(self, node): + '''Traverses the subtree of a DOM node, and register a tclib message for + all the <message> nodes. + ''' + att_text = [] + if node.attributes: + items = node.attributes.items() + items.sort() + for key, value in items: + att_text.append(' %s=\"%s\"' % (key, value)) + self._AddNontranslateableChunk("<%s%s>" % + (node.tagName, ''.join(att_text))) + if node.tagName == 'message': + msg = tclib.Message(description=node.attributes['desc']) + for child in node.childNodes: + if child.nodeType == minidom.Node.TEXT_NODE: + if msg == None: + self._AddNontranslateableChunk(child.data) + else: + msg.AppendText(child.data) + elif child.nodeType == minidom.Node.ELEMENT_NODE: + if child.tagName == 'ph': + self._ParsePlaceholder(child, msg) + else: + assert False + self.skeleton_.append(self.uberclique.MakeClique(msg)) + else: + for child in node.childNodes: + if child.nodeType == minidom.Node.TEXT_NODE: + self._AddNontranslateableChunk(child.data) + elif node.nodeType == minidom.Node.ELEMENT_NODE: + self._ParseNode(child) + + self._AddNontranslateableChunk("</%s>" % node.tagName) + + def _AddIndentedNontranslateableChunk(self, depth, string): + '''Adds a nontranslateable chunk of text to the internally stored output. + + Args: + depth: The number of double spaces to prepend to the next argument string. + string: The chunk of text to add. + ''' + result = [] + while depth > 0: + result.append(' ') + depth = depth - 1 + result.append(string) + self._AddNontranslateableChunk(''.join(result)) + + def _GetDescription(self, item, item_type, parent_item, key): + '''Creates a description for a translatable message. The description gives + some context for the person who will translate this message. + + Args: + item: A policy or an enumeration item. + item_type: 'enum_item' | 'policy' + parent_item: The owner of item. (A policy of type group or enum.) + key: The name of the key to parse. + depth: The level of indentation. + ''' + key_map = { + 'desc': 'Description', + 'caption': 'Caption', + 'label': 'Label', + } + if type == 'policy': + return '%s of the policy named %s' % (key_map[key], item['name']) + elif type == 'enum_item': + return ('%s of the option named %s in policy %s' % + (key_map[key], item['name'], parent_item['name'])) + + def _AddPolicyKey(self, item, item_type, parent_item, key, depth): + '''Given a policy/enumeration item and a key, adds that key and its value + into the output. + E.g.: + 'example_value': 123 + If key indicates that the value is a translatable string, then it is parsed + as a translatable string. + + Args: + item: A policy or an enumeration item. + item_type: 'enum_item' | 'policy' + parent_item: The owner of item. (A policy of type group or enum.) + key: The name of the key to parse. + depth: The level of indentation. + ''' + self._AddIndentedNontranslateableChunk(depth, "'%s': " % key) + if key in ('desc', 'caption', 'label'): + self._AddNontranslateableChunk("'''") + self._ParseMessage( + item[key], + self._GetDescription(item, item_type, parent_item, key)) + self._AddNontranslateableChunk("''',\n") + else: + str_val = item[key] + if type(str_val) == types.StringType: + str_val = "'%s'" % str_val + else: + str_val = str(str_val) + self._AddNontranslateableChunk(str_val + ',\n') + + def _AddItems(self, items, item_type, parent_item, depth): + '''Parses and adds a list of items from the JSON file. Items can be policies + or parts of an enum policy. + + Args: + items: Either a list of policies or a list of dictionaries. + item_type: 'enum_item' | 'policy' + parent_item: If items contains a list of policies, then this is the policy + group that owns them. If items contains a list of enumeration items, + then this is the enum policy that holds them. + depth: Indicates the depth of our position in the JSON hierarchy. Used to + add nice line-indent to the output. + ''' + for item1 in items: + self._AddIndentedNontranslateableChunk(depth, "{\n") + for key in item1.keys(): + if key == 'items': + self._AddIndentedNontranslateableChunk(depth + 1, "'items': [\n") + self._AddItems(item1['items'], 'enum_item', item1, depth + 2) + self._AddIndentedNontranslateableChunk(depth + 1, "],\n") + elif key == 'policies': + self._AddIndentedNontranslateableChunk(depth + 1, "'policies': [\n") + self._AddItems(item1['policies'], 'policy', item1, depth + 2) + self._AddIndentedNontranslateableChunk(depth + 1, "],\n") + else: + self._AddPolicyKey(item1, item_type, parent_item, key, depth + 1) + self._AddIndentedNontranslateableChunk(depth, "},\n") + + def _AddMessages(self): + '''Processed and adds the 'messages' section to the output.''' + self._AddNontranslateableChunk(" 'messages': {\n") + for name, message in self.data['messages'].iteritems(): + self._AddNontranslateableChunk(" '%s': {\n" % name) + self._AddNontranslateableChunk(" 'text': '''") + self._ParseMessage(message['text'], message['desc']) + self._AddNontranslateableChunk("'''\n") + self._AddNontranslateableChunk(" },\n") + self._AddNontranslateableChunk(" },\n") + + def _AddPlaceholders(self): + '''Adds the 'placeholders' section to the output.''' + self._AddNontranslateableChunk(" 'placeholders':\n") + self._AddNontranslateableChunk( + pprint.pformat(self.data['placeholders'], indent=2, depth=2)) + + # Although we use the RegexpGatherer base class, we do not use the + # _RegExpParse method of that class to implement Parse(). Instead, we + # parse using a DOM parser. + def Parse(self): + if (self.have_parsed_): + return + self.have_parsed_ = True + + self.data = eval(self.text_) + + self._AddNontranslateableChunk('{\n') + self._AddNontranslateableChunk(" 'policy_definitions': [\n") + self._AddItems(self.data['policy_definitions'], 'policy', None, 2) + self._AddNontranslateableChunk(" ],\n") + self._AddMessages() + self._AddPlaceholders() + self._AddNontranslateableChunk('\n}') + + def Escape(self, text): + # \ -> \\ + # ' -> \' + # " -> \" + return text.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'") + + def FromFile(filename_or_stream, extkey=None, encoding='cp1252'): + if isinstance(filename_or_stream, types.StringTypes): + if util.IsVerbose(): + print "PolicyJson reading file %s, encoding %s" % ( + filename_or_stream, encoding) + filename_or_stream = \ + util.WrapInputStream(file(filename_or_stream, 'r'), encoding) + return PolicyJson(filename_or_stream.read()) + FromFile = staticmethod(FromFile) diff --git a/tools/grit/grit/gather/policy_json_unittest.py b/tools/grit/grit/gather/policy_json_unittest.py new file mode 100644 index 0000000..3df43a0 --- /dev/null +++ b/tools/grit/grit/gather/policy_json_unittest.py @@ -0,0 +1,178 @@ +#!/usr/bin/python2.4 +# Copyright (c) 2011 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +'''Unit tests for grit.gather.policy_json''' + +import os +import re +import sys +if __name__ == '__main__': + sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), '../..')) + +import unittest + +from grit.gather import muppet_strings +from grit.gather import policy_json + +class PolicyJsonUnittest(unittest.TestCase): + + def GetExpectedOutput(self, original): + expected = eval(original) + for key, message in expected['messages'].iteritems(): + del message['desc'] + return expected + + def testEmpty(self): + original = "{'policy_definitions': [], 'placeholders': [], 'messages': {}}" + gatherer = policy_json.PolicyJson(original) + gatherer.Parse() + self.failUnless(len(gatherer.GetCliques()) == 0) + self.failUnless(eval(original) == eval(gatherer.Translate('en'))) + + def testGeneralPolicy(self): + original = ( + "{" + " 'policy_definitions': [" + " {" + " 'name': 'HomepageLocation'," + " 'type': 'string'," + " 'supported_on': ['chrome.*:8-']," + " 'annotations': {" + " 'features': {'dynamic_refresh': 1}," + " 'example_value': 'http://chromium.org'," + " }," + " 'caption': 'nothing special 1'," + " 'desc': 'nothing special 2'," + " 'label': 'nothing special 3'," + " }," + " ]," + " 'placeholders': []," + " 'messages': {" + " 'msg_identifier': {" + " 'text': 'nothing special 3'," + " 'desc': 'nothing special descr 3'," + " }" + " }" + "}") + gatherer = policy_json.PolicyJson(original) + gatherer.Parse() + self.failUnless(len(gatherer.GetCliques()) == 4) + expected = self.GetExpectedOutput(original) + self.failUnless(expected == eval(gatherer.Translate('en'))) + + def testEnum(self): + original = ( + "{" + " 'policy_definitions': [" + " {" + " 'items': [" + " {" + " 'caption': 'nothing special'," + " }" + " ]" + " }," + " ]," + " 'placeholders': []," + " 'messages': {}" + "}") + gatherer = policy_json.PolicyJson(original) + gatherer.Parse() + self.failUnless(len(gatherer.GetCliques()) == 1) + expected = self.GetExpectedOutput(original) + self.failUnless(expected == eval(gatherer.Translate('en'))) + + def testSubPolicy(self): + original = ( + "{" + " 'policy_definitions': [" + " {" + " 'policies': [" + " {" + " 'caption': 'nothing special'," + " }" + " ]" + " }," + " ]," + " 'placeholders': []," + " 'messages': {}" + "}") + gatherer = policy_json.PolicyJson(original) + gatherer.Parse() + self.failUnless(len(gatherer.GetCliques()) == 1) + expected = self.GetExpectedOutput(original) + self.failUnless(expected == eval(gatherer.Translate('en'))) + + def testEscapingAndLineBreaks(self): + original = """{ + 'policy_definitions': [], + 'placeholders': [], + 'messages': { + 'msg1': { + # The following line will contain two backslash characters when it + # ends up in eval(). + 'text': '''backslashes, Sir? \\\\''', + 'desc': '', + }, + 'msg2': { + 'text': '''quotes, Madam? "''', + 'desc': '', + }, + 'msg3': { + # The following line will contain two backslash characters when it + # ends up in eval(). + 'text': 'backslashes, Sir? \\\\', + 'desc': '', + }, + 'msg4': { + 'text': "quotes, Madam? '", + 'desc': '', + }, + 'msg5': { + 'text': '''what happens +with a newline?''', + 'desc': '' + }, + 'msg6': { + # The following line will contain a backslash+n when it ends up in + # eval(). + 'text': 'what happens\\nwith a newline? (Episode 1)', + 'desc': '' + } + } +}""" + gatherer = policy_json.PolicyJson(original) + gatherer.Parse() + self.failUnless(len(gatherer.GetCliques()) == 6) + expected = self.GetExpectedOutput(original) + self.failUnless(expected == eval(gatherer.Translate('en'))) + + def testPlaceholders(self): + original = """{ + 'policy_definitions': [ + { + 'caption': '''Please install + <ph name="PRODUCT_NAME">$1<ex>Google Chrome</ex></ph>.''', + }, + ], + 'placeholders': [], + 'messages': {} +}""" + gatherer = policy_json.PolicyJson(original) + gatherer.Parse() + self.failUnless(len(gatherer.GetCliques()) == 1) + expected = eval(re.sub('<ph.*ph>', '$1', original)) + self.failUnless(expected == eval(gatherer.Translate('en'))) + self.failUnless(gatherer.GetCliques()[0].translateable) + msg = gatherer.GetCliques()[0].GetMessage() + self.failUnless(len(msg.GetPlaceholders()) == 1) + ph = msg.GetPlaceholders()[0] + self.failUnless(ph.GetOriginal() == '$1') + self.failUnless(ph.GetPresentation() == 'PRODUCT_NAME') + self.failUnless(ph.GetExample() == 'Google Chrome') + + +if __name__ == '__main__': + unittest.main() + diff --git a/tools/grit/grit/gather/regexp.py b/tools/grit/grit/gather/regexp.py index 88c7413..150a777 100644 --- a/tools/grit/grit/gather/regexp.py +++ b/tools/grit/grit/gather/regexp.py @@ -9,12 +9,12 @@ import re import types -from grit.gather import interface +from grit.gather import skeleton_gatherer from grit import clique from grit import tclib -class RegexpGatherer(interface.GathererBase): +class RegexpGatherer(skeleton_gatherer.SkeletonGatherer): '''Common functionality of gatherers based on parsing using a single regular expression. ''' @@ -32,81 +32,9 @@ class RegexpGatherer(interface.GathererBase): } def __init__(self, text): - interface.GathererBase.__init__(self) + skeleton_gatherer.SkeletonGatherer.__init__(self) # Original text of what we're parsing self.text_ = text.strip() - # List of parts of the document. Translateable parts are clique.MessageClique - # objects, nontranslateable parts are plain strings. Translated messages are - # inserted back into the skeleton using the quoting rules defined by - # self.Escape() - self.skeleton_ = [] - # A list of the names of IDs that need to be defined for this resource - # section to compile correctly. - self.ids_ = [] - # True if Parse() has already been called. - self.have_parsed_ = False - # True if a translatable chunk has been added - self.translatable_chunk_ = False - # If not None, all parts of the document will be put into this single - # message; otherwise the normal skeleton approach is used. - self.single_message_ = None - # Number to use for the next placeholder name. Used only if single_message - # is not None - self.ph_counter_ = 1 - - def GetText(self): - '''Returns the original text of the section''' - return self.text_ - - def Escape(self, text): - '''Subclasses can override. Base impl is identity. - ''' - return text - - def UnEscape(self, text): - '''Subclasses can override. Base impl is identity. - ''' - return text - - def GetTextualIds(self): - '''Returns the list of textual IDs that need to be defined for this - resource section to compile correctly.''' - return self.ids_ - - def GetCliques(self): - '''Returns the message cliques for each translateable message in the - resource section.''' - return filter(lambda x: isinstance(x, clique.MessageClique), self.skeleton_) - - def Translate(self, lang, pseudo_if_not_available=True, - skeleton_gatherer=None, fallback_to_english=False): - if len(self.skeleton_) == 0: - raise exception.NotReady() - if skeleton_gatherer: - assert len(skeleton_gatherer.skeleton_) == len(self.skeleton_) - - out = [] - for ix in range(len(self.skeleton_)): - if isinstance(self.skeleton_[ix], types.StringTypes): - if skeleton_gatherer: - # Make sure the skeleton is like the original - assert(isinstance(skeleton_gatherer.skeleton_[ix], types.StringTypes)) - out.append(skeleton_gatherer.skeleton_[ix]) - else: - out.append(self.skeleton_[ix]) - else: - if skeleton_gatherer: # Make sure the skeleton is like the original - assert(not isinstance(skeleton_gatherer.skeleton_[ix], - types.StringTypes)) - msg = self.skeleton_[ix].MessageForLanguage(lang, - pseudo_if_not_available, - fallback_to_english) - - def MyEscape(text): - return self.Escape(text) - text = msg.GetRealContent(escaping_function=MyEscape) - out.append(text) - return ''.join(out) # Contextualization elements. Used for adding additional information # to the message bundle description string from RC files. @@ -122,37 +50,6 @@ class RegexpGatherer(interface.GathererBase): message = self.skeleton_[len(self.skeleton_) - 1].GetMessage() message.SetDescription(description) - def Parse(self): - '''Parses the section. Implemented by subclasses. Idempotent.''' - raise NotImplementedError() - - def _AddNontranslateableChunk(self, chunk): - '''Adds a nontranslateable chunk.''' - if self.single_message_: - ph = tclib.Placeholder('XX%02dXX' % self.ph_counter_, chunk, chunk) - self.ph_counter_ += 1 - self.single_message_.AppendPlaceholder(ph) - else: - self.skeleton_.append(chunk) - - def _AddTranslateableChunk(self, chunk): - '''Adds a translateable chunk. It will be unescaped before being added.''' - # We don't want empty messages since they are redundant and the TC - # doesn't allow them. - if chunk == '': - return - - unescaped_text = self.UnEscape(chunk) - if self.single_message_: - self.single_message_.AppendText(unescaped_text) - else: - self.skeleton_.append(self.uberclique.MakeClique( - tclib.Message(text=unescaped_text))) - self.translatable_chunk_ = True - - def _AddTextualId(self, id): - self.ids_.append(id) - def _RegExpParse(self, regexp, text_to_parse): '''An implementation of Parse() that can be used for resource sections that can be parsed using a single multi-line regular expression. diff --git a/tools/grit/grit/gather/skeleton_gatherer.py b/tools/grit/grit/gather/skeleton_gatherer.py new file mode 100644 index 0000000..15cb3f3 --- /dev/null +++ b/tools/grit/grit/gather/skeleton_gatherer.py @@ -0,0 +1,127 @@ +#!/usr/bin/python2.4 +# Copyright (c) 2011 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +'''A baseclass for simple gatherers that store their gathered resource in a +list. +''' + +import re +import types + +from grit.gather import interface +from grit import clique +from grit import tclib + + +class SkeletonGatherer(interface.GathererBase): + '''Common functionality of gatherers that parse their input as a skeleton of + translatable and nontranslatable chunks. + ''' + + def __init__(self): + interface.GathererBase.__init__(self) + # List of parts of the document. Translateable parts are + # clique.MessageClique objects, nontranslateable parts are plain strings. + # Translated messages are inserted back into the skeleton using the quoting + # rules defined by self.Escape() + self.skeleton_ = [] + # A list of the names of IDs that need to be defined for this resource + # section to compile correctly. + self.ids_ = [] + # True if Parse() has already been called. + self.have_parsed_ = False + # True if a translatable chunk has been added + self.translatable_chunk_ = False + # If not None, all parts of the document will be put into this single + # message; otherwise the normal skeleton approach is used. + self.single_message_ = None + # Number to use for the next placeholder name. Used only if single_message + # is not None + self.ph_counter_ = 1 + + def GetText(self): + '''Returns the original text of the section''' + return self.text_ + + def Escape(self, text): + '''Subclasses can override. Base impl is identity. + ''' + return text + + def UnEscape(self, text): + '''Subclasses can override. Base impl is identity. + ''' + return text + + def GetTextualIds(self): + '''Returns the list of textual IDs that need to be defined for this + resource section to compile correctly.''' + return self.ids_ + + def _AddTextualId(self, id): + self.ids_.append(id) + + def GetCliques(self): + '''Returns the message cliques for each translateable message in the + resource section.''' + return filter(lambda x: isinstance(x, clique.MessageClique), self.skeleton_) + + def Translate(self, lang, pseudo_if_not_available=True, + skeleton_gatherer=None, fallback_to_english=False): + if len(self.skeleton_) == 0: + raise exception.NotReady() + if skeleton_gatherer: + assert len(skeleton_gatherer.skeleton_) == len(self.skeleton_) + + out = [] + for ix in range(len(self.skeleton_)): + if isinstance(self.skeleton_[ix], types.StringTypes): + if skeleton_gatherer: + # Make sure the skeleton is like the original + assert(isinstance(skeleton_gatherer.skeleton_[ix], types.StringTypes)) + out.append(skeleton_gatherer.skeleton_[ix]) + else: + out.append(self.skeleton_[ix]) + else: + if skeleton_gatherer: # Make sure the skeleton is like the original + assert(not isinstance(skeleton_gatherer.skeleton_[ix], + types.StringTypes)) + msg = self.skeleton_[ix].MessageForLanguage(lang, + pseudo_if_not_available, + fallback_to_english) + + def MyEscape(text): + return self.Escape(text) + text = msg.GetRealContent(escaping_function=MyEscape) + out.append(text) + return ''.join(out) + + def Parse(self): + '''Parses the section. Implemented by subclasses. Idempotent.''' + raise NotImplementedError() + + def _AddNontranslateableChunk(self, chunk): + '''Adds a nontranslateable chunk.''' + if self.single_message_: + ph = tclib.Placeholder('XX%02dXX' % self.ph_counter_, chunk, chunk) + self.ph_counter_ += 1 + self.single_message_.AppendPlaceholder(ph) + else: + self.skeleton_.append(chunk) + + def _AddTranslateableChunk(self, chunk): + '''Adds a translateable chunk. It will be unescaped before being added.''' + # We don't want empty messages since they are redundant and the TC + # doesn't allow them. + if chunk == '': + return + + unescaped_text = self.UnEscape(chunk) + if self.single_message_: + self.single_message_.AppendText(unescaped_text) + else: + self.skeleton_.append(self.uberclique.MakeClique( + tclib.Message(text=unescaped_text))) + self.translatable_chunk_ = True diff --git a/tools/grit/grit/node/structure.py b/tools/grit/grit/node/structure.py index 95eac76..8d5e381 100644 --- a/tools/grit/grit/node/structure.py +++ b/tools/grit/grit/node/structure.py @@ -1,5 +1,5 @@ #!/usr/bin/python2.4 -# Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. @@ -15,12 +15,12 @@ from grit import constants from grit import exception from grit import util -import grit.gather.json_loader import grit.gather.rc import grit.gather.tr_html import grit.gather.admin_template import grit.gather.txt import grit.gather.muppet_strings +import grit.gather.policy_json import grit.format.rc import grit.format.rc_header @@ -45,7 +45,7 @@ _GATHERERS = { 'tr_html' : grit.gather.tr_html.TrHtml, 'txt' : grit.gather.txt.TxtFile, 'version' : grit.gather.rc.Version, - 'policy_template_metafile' : grit.gather.json_loader.JsonLoader, + 'policy_template_metafile' : grit.gather.policy_json.PolicyJson, } diff --git a/tools/grit/grit/test_suite_all.py b/tools/grit/grit/test_suite_all.py index e6691d5..df11bf0 100644 --- a/tools/grit/grit/test_suite_all.py +++ b/tools/grit/grit/test_suite_all.py @@ -44,19 +44,9 @@ class TestSuiteAll(unittest.TestSuite): from grit.tool import postprocess_unittest from grit import shortcuts_unittests from grit.gather import muppet_strings_unittest + from grit.gather import policy_json_unittest from grit.node.custom import filename_unittest import grit.format.js_map_format_unittest - from grit.format.policy_templates import policy_template_generator_unittest - from grit.format.policy_templates.writers import plist_writer_unittest - from grit.format.policy_templates.writers \ - import plist_strings_writer_unittest - from grit.format.policy_templates.writers \ - import adm_writer_unittest - from grit.format.policy_templates.writers \ - import adml_writer_unittest - from grit.format.policy_templates.writers \ - import admx_writer_unittest - from grit.format.policy_templates.writers import doc_writer_unittest test_classes = [ base_unittest.NodeUnittest, @@ -86,13 +76,7 @@ class TestSuiteAll(unittest.TestSuite): muppet_strings_unittest.MuppetStringsUnittest, filename_unittest.WindowsFilenameUnittest, grit.format.js_map_format_unittest.JsMapFormatUnittest, - policy_template_generator_unittest.PolicyTemplateGeneratorUnittest, - plist_writer_unittest.PListWriterUnittest, - plist_strings_writer_unittest.PListStringsWriterUnittest, - adm_writer_unittest.AdmWriterUnittest, - admx_writer_unittest.AdmxWriterUnittest, - adml_writer_unittest.AdmlWriterUnittest, - doc_writer_unittest.DocWriterUnittest, + policy_json_unittest.PolicyJsonUnittest, # add test classes here... ] |