Home | History | Annotate | Download | only in format
      1 #!/usr/bin/env python
      2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
      3 # Use of this source code is governed by a BSD-style license that can be
      4 # found in the LICENSE file.
      5 
      6 """Formats as a .js file using a map: <english text> -> <localized text>.
      7 """
      8 
      9 import re
     10 
     11 from grit import util
     12 
     13 
     14 """The required preamble for JS files."""
     15 _HEADER = '// This file is automatically generated by GRIT.  Do not edit.\n'
     16 
     17 
     18 def Format(root, lang='en', output_dir='.'):
     19   from grit.node import empty, message
     20   yield _HEADER
     21   for item in root.ActiveDescendants():
     22     with item:
     23       if isinstance(item, message.MessageNode):
     24         yield _FormatMessage(item, lang)
     25       elif isinstance(item, empty.MessagesNode):
     26         yield '\n'
     27 
     28 
     29 def _FormatMessage(item, lang):
     30   """Format a single message."""
     31 
     32   en_message = item.ws_at_start + item.Translate('en') + item.ws_at_end
     33   # Remove position numbers from placeholders.
     34   en_message = re.sub(r'%\d\$([a-z])', r'%\1', en_message)
     35   # Escape double quotes.
     36   en_message = re.sub(r'\\', r'\\\\', en_message)
     37   en_message = re.sub(r'"', r'\"', en_message)
     38 
     39   loc_message = item.ws_at_start + item.Translate(lang) + item.ws_at_end
     40   # Escape double quotes.
     41   loc_message = re.sub(r'\\', r'\\\\', loc_message)
     42   loc_message = re.sub(r'"', r'\"', loc_message)
     43 
     44   return '\nlocalizedStrings["%s"] = "%s";' % (en_message, loc_message)
     45