PageRenderTime 387ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/tools/grit/grit/format/policy_templates/template_formatter.py

https://github.com/Gitman1989/chromium
Python | 123 lines | 111 code | 5 blank | 7 comment | 0 complexity | 76dd16ee9975b9757c2b03c5e2adc496 MD5 | raw file
  1. # Copyright (c) 2010 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. import os
  5. import sys
  6. import types
  7. from grit.format import interface
  8. from grit.format.policy_templates import policy_template_generator
  9. from grit.format.policy_templates import writer_configuration
  10. from grit.node import structure
  11. from grit.node import message
  12. from grit.node import misc
  13. class TemplateFormatter(interface.ItemFormatter):
  14. '''Creates a template file corresponding to an <output> node of the grit
  15. tree.
  16. More precisely, processes the whole grit tree for a given <output> node whose
  17. type is 'adm'. TODO(gfeher) add new types here
  18. The result of processing is a policy template file with the
  19. given type and language of the <output> node. A new instance of this class
  20. is created by grit.misc.GritNode for each <output> node. This class does
  21. the interfacing with grit, but the actual template-generating work is done in
  22. policy_template_generator.PolicyTemplateGenerator.
  23. '''
  24. def __init__(self, writer_name):
  25. '''Initializes this formatter to output messages with a given writer.
  26. Args:
  27. writer_name: A string identifying the TemplateWriter subclass used
  28. for generating the output. If writer name is 'adm', then the class
  29. from module 'writers.adm_writer' will be used.
  30. '''
  31. super(type(self), self).__init__()
  32. writer_module_name = \
  33. 'grit.format.policy_templates.writers.' + writer_name + '_writer'
  34. __import__(writer_module_name)
  35. # The module that contains the writer class:
  36. self._writer_module = sys.modules[writer_module_name]
  37. def Format(self, item, lang='en', begin_item=True, output_dir='.'):
  38. '''Generates a template corresponding to an <output> node in the grd file.
  39. Args:
  40. item: the <grit> root node of the grit tree.
  41. lang: the language of outputted text, e.g.: 'en'
  42. begin_item: True or False, depending on if this function was called at
  43. the beginning or at the end of the item.
  44. output_dir: The output directory, currently unused here.
  45. Returns:
  46. The text of the template file.
  47. '''
  48. if not begin_item:
  49. return ''
  50. self._lang = lang
  51. self._config = writer_configuration.GetConfigurationForBuild(item.defines)
  52. self._policy_data = None
  53. self._messages = {}
  54. self._ParseGritNodes(item)
  55. return self._GetOutput()
  56. def _GetOutput(self):
  57. '''Generates a template file using the instance variables initialized
  58. in Format() using the writer specified in __init__().
  59. Returns:
  60. The text of the policy template based on the parameters passed
  61. to __init__() and Format().
  62. '''
  63. policy_generator = policy_template_generator.PolicyTemplateGenerator(
  64. self._messages,
  65. self._policy_data['policy_definitions'])
  66. writer = self._writer_module.GetWriter(self._config, self._messages)
  67. str = policy_generator.GetTemplateText(writer)
  68. return str
  69. def _ImportMessage(self, message):
  70. '''Takes a grit message node and adds its translated content to
  71. self._messages.
  72. Args:
  73. message: A <message> node in the grit tree.
  74. '''
  75. msg_name = message.GetTextualIds()[0]
  76. # Get translation of message.
  77. msg_txt = message.Translate(self._lang)
  78. # Replace the placeholder of app name.
  79. msg_txt = msg_txt.replace('$1', self._config['app_name'])
  80. msg_txt = msg_txt.replace('$3', self._config['frame_name'])
  81. # Replace other placeholders.
  82. for placeholder in self._policy_data['placeholders']:
  83. msg_txt = msg_txt.replace(placeholder['key'], placeholder['value'])
  84. # Strip spaces and escape newlines.
  85. lines = msg_txt.split('\n')
  86. lines = [line.strip() for line in lines]
  87. msg_txt = "\n".join(lines)
  88. self._messages[msg_name] = msg_txt
  89. def _ParseGritNodes(self, item):
  90. '''Collects the necessary information from the grit tree:
  91. the message strings and the policy definitions.
  92. Args:
  93. item: The grit node parsed currently.
  94. '''
  95. nodes = []
  96. if (isinstance(item, misc.IfNode) and not item.IsConditionSatisfied()):
  97. return
  98. if (isinstance(item, structure.StructureNode) and
  99. item.attrs['type'] == 'policy_template_metafile'):
  100. assert self._policy_data == None
  101. self._policy_data = item.gatherer.GetData()
  102. elif (isinstance(item, message.MessageNode)):
  103. self._ImportMessage(item)
  104. for child in item.children:
  105. self._ParseGritNodes(child)