PageRenderTime 55ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/tools/grit/grit/node/misc.py

https://github.com/nachoalthabe/chromium
Python | 272 lines | 237 code | 17 blank | 18 comment | 12 complexity | 890b05e5a95adb751cb74d28644bc57e MD5 | raw file
  1. #!/usr/bin/python2.4
  2. # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. '''Miscellaneous node types.
  6. '''
  7. import os.path
  8. from grit.node import base
  9. from grit.node import message
  10. from grit import exception
  11. from grit import constants
  12. from grit import util
  13. import grit.format.rc_header
  14. class IfNode(base.Node):
  15. '''A node for conditional inclusion of resources.
  16. '''
  17. def _IsValidChild(self, child):
  18. from grit.node import empty
  19. assert self.parent, '<if> node should never be root.'
  20. if isinstance(self.parent, empty.IncludesNode):
  21. from grit.node import include
  22. return isinstance(child, include.IncludeNode)
  23. elif isinstance(self.parent, empty.MessagesNode):
  24. from grit.node import message
  25. return isinstance(child, message.MessageNode)
  26. elif isinstance(self.parent, empty.StructuresNode):
  27. from grit.node import structure
  28. return isinstance(child, structure.StructureNode)
  29. else:
  30. return False
  31. def MandatoryAttributes(self):
  32. return ['expr']
  33. def IsConditionSatisfied(self):
  34. '''Returns true if and only if the Python expression stored in attribute
  35. 'expr' evaluates to true.
  36. '''
  37. return self.EvaluateCondition(self.attrs['expr'])
  38. class ReleaseNode(base.Node):
  39. '''The <release> element.'''
  40. def _IsValidChild(self, child):
  41. from grit.node import empty
  42. return isinstance(child, (empty.IncludesNode, empty.MessagesNode,
  43. empty.StructuresNode, empty.IdentifiersNode))
  44. def _IsValidAttribute(self, name, value):
  45. return (
  46. (name == 'seq' and int(value) <= self.GetRoot().GetCurrentRelease()) or
  47. name == 'allow_pseudo'
  48. )
  49. def MandatoryAttributes(self):
  50. return ['seq']
  51. def DefaultAttributes(self):
  52. return { 'allow_pseudo' : 'true' }
  53. def GetReleaseNumber():
  54. '''Returns the sequence number of this release.'''
  55. return self.attribs['seq']
  56. def ItemFormatter(self, t):
  57. if t == 'data_package':
  58. from grit.format import data_pack
  59. return data_pack.DataPack()
  60. else:
  61. return super(type(self), self).ItemFormatter(t)
  62. class GritNode(base.Node):
  63. '''The <grit> root element.'''
  64. def __init__(self):
  65. base.Node.__init__(self)
  66. self.output_language = ''
  67. self.defines = {}
  68. def _IsValidChild(self, child):
  69. from grit.node import empty
  70. return isinstance(child, (ReleaseNode, empty.TranslationsNode,
  71. empty.OutputsNode))
  72. def _IsValidAttribute(self, name, value):
  73. if name not in ['base_dir', 'source_lang_id',
  74. 'latest_public_release', 'current_release',
  75. 'enc_check', 'tc_project']:
  76. return False
  77. if name in ['latest_public_release', 'current_release'] and value.strip(
  78. '0123456789') != '':
  79. return False
  80. return True
  81. def MandatoryAttributes(self):
  82. return ['latest_public_release', 'current_release']
  83. def DefaultAttributes(self):
  84. return {
  85. 'base_dir' : '.',
  86. 'source_lang_id' : 'en',
  87. 'enc_check' : constants.ENCODING_CHECK,
  88. 'tc_project' : 'NEED_TO_SET_tc_project_ATTRIBUTE',
  89. }
  90. def EndParsing(self):
  91. base.Node.EndParsing(self)
  92. if (int(self.attrs['latest_public_release'])
  93. > int(self.attrs['current_release'])):
  94. raise exception.Parsing('latest_public_release cannot have a greater '
  95. 'value than current_release')
  96. self.ValidateUniqueIds()
  97. # Add the encoding check if it's not present (should ensure that it's always
  98. # present in all .grd files generated by GRIT). If it's present, assert if
  99. # it's not correct.
  100. if 'enc_check' not in self.attrs or self.attrs['enc_check'] == '':
  101. self.attrs['enc_check'] = constants.ENCODING_CHECK
  102. else:
  103. assert self.attrs['enc_check'] == constants.ENCODING_CHECK, (
  104. 'Are you sure your .grd file is in the correct encoding (UTF-8)?')
  105. def ValidateUniqueIds(self):
  106. '''Validate that 'name' attribute is unique in all nodes in this tree
  107. except for nodes that are children of <if> nodes.
  108. '''
  109. unique_names = {}
  110. duplicate_names = []
  111. for node in self:
  112. if isinstance(node, message.PhNode):
  113. continue # PhNode objects have a 'name' attribute which is not an ID
  114. node_ids = node.GetTextualIds()
  115. if node_ids:
  116. for node_id in node_ids:
  117. if util.SYSTEM_IDENTIFIERS.match(node_id):
  118. continue # predefined IDs are sometimes used more than once
  119. # Don't complain about duplicate IDs if they occur in a node that is
  120. # inside an <if> node.
  121. if (node_id in unique_names and node_id not in duplicate_names and
  122. (not node.parent or not isinstance(node.parent, IfNode))):
  123. duplicate_names.append(node_id)
  124. unique_names[node_id] = 1
  125. if len(duplicate_names):
  126. raise exception.DuplicateKey(', '.join(duplicate_names))
  127. def GetCurrentRelease(self):
  128. '''Returns the current release number.'''
  129. return int(self.attrs['current_release'])
  130. def GetLatestPublicRelease(self):
  131. '''Returns the latest public release number.'''
  132. return int(self.attrs['latest_public_release'])
  133. def GetSourceLanguage(self):
  134. '''Returns the language code of the source language.'''
  135. return self.attrs['source_lang_id']
  136. def GetTcProject(self):
  137. '''Returns the name of this project in the TranslationConsole, or
  138. 'NEED_TO_SET_tc_project_ATTRIBUTE' if it is not defined.'''
  139. return self.attrs['tc_project']
  140. def SetOwnDir(self, dir):
  141. '''Informs the 'grit' element of the directory the file it is in resides.
  142. This allows it to calculate relative paths from the input file, which is
  143. what we desire (rather than from the current path).
  144. Args:
  145. dir: r'c:\bla'
  146. Return:
  147. None
  148. '''
  149. assert dir
  150. self.base_dir = os.path.normpath(os.path.join(dir, self.attrs['base_dir']))
  151. def GetBaseDir(self):
  152. '''Returns the base directory, relative to the working directory. To get
  153. the base directory as set in the .grd file, use GetOriginalBaseDir()
  154. '''
  155. if hasattr(self, 'base_dir'):
  156. return self.base_dir
  157. else:
  158. return self.GetOriginalBaseDir()
  159. def GetOriginalBaseDir(self):
  160. '''Returns the base directory, as set in the .grd file.
  161. '''
  162. return self.attrs['base_dir']
  163. def GetOutputFiles(self):
  164. '''Returns the list of <file> nodes that are children of this node's
  165. <outputs> child.'''
  166. for child in self.children:
  167. if child.name == 'outputs':
  168. return child.children
  169. raise exception.MissingElement()
  170. def ItemFormatter(self, t):
  171. if t == 'rc_header':
  172. from grit.format import rc_header # import here to avoid circular dep
  173. return rc_header.TopLevel()
  174. elif t in ['rc_all', 'rc_translateable', 'rc_nontranslateable']:
  175. from grit.format import rc # avoid circular dep
  176. return rc.TopLevel()
  177. elif t == 'resource_map_header':
  178. from grit.format import resource_map
  179. return resource_map.HeaderTopLevel()
  180. elif t == 'resource_map_source':
  181. from grit.format import resource_map
  182. return resource_map.SourceTopLevel()
  183. else:
  184. return super(type(self), self).ItemFormatter(t)
  185. def SetOutputContext(self, output_language, defines):
  186. self.output_language = output_language
  187. self.defines = defines
  188. class IdentifierNode(base.Node):
  189. '''A node for specifying identifiers that should appear in the resource
  190. header file, and be unique amongst all other resource identifiers, but don't
  191. have any other attributes or reference any resources.
  192. '''
  193. def MandatoryAttributes(self):
  194. return ['name']
  195. def DefaultAttributes(self):
  196. return { 'comment' : '', 'id' : '' }
  197. def ItemFormatter(self, t):
  198. if t == 'rc_header':
  199. return grit.format.rc_header.Item()
  200. def GetId(self):
  201. '''Returns the id of this identifier if it has one, None otherwise
  202. '''
  203. if 'id' in self.attrs:
  204. return self.attrs['id']
  205. return None
  206. # static method
  207. def Construct(parent, name, id, comment):
  208. '''Creates a new node which is a child of 'parent', with attributes set
  209. by parameters of the same name.
  210. '''
  211. node = IdentifierNode()
  212. node.StartParsing('identifier', parent)
  213. node.HandleAttribute('name', name)
  214. node.HandleAttribute('id', id)
  215. node.HandleAttribute('comment', comment)
  216. node.EndParsing()
  217. return node
  218. Construct = staticmethod(Construct)