create_messages.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. #!/usr/bin/python
  2. # Generate .js files defining Blockly core and language messages.
  3. #
  4. # Copyright 2013 Google Inc.
  5. # https://developers.google.com/blockly/
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. import argparse
  19. import codecs
  20. import os
  21. import re
  22. import sys
  23. from common import read_json_file
  24. _NEWLINE_PATTERN = re.compile('[\n\r]')
  25. def string_is_ascii(s):
  26. try:
  27. s.decode('ascii')
  28. return True
  29. except UnicodeEncodeError:
  30. return False
  31. def main():
  32. """Generate .js files defining Blockly core and language messages."""
  33. # Process command-line arguments.
  34. parser = argparse.ArgumentParser(description='Convert JSON files to JS.')
  35. parser.add_argument('--source_lang', default='en',
  36. help='ISO 639-1 source language code')
  37. parser.add_argument('--source_lang_file',
  38. default=os.path.join('json', 'en.json'),
  39. help='Path to .json file for source language')
  40. parser.add_argument('--source_synonym_file',
  41. default=os.path.join('json', 'synonyms.json'),
  42. help='Path to .json file with synonym definitions')
  43. parser.add_argument('--output_dir', default='js/',
  44. help='relative directory for output files')
  45. parser.add_argument('--key_file', default='keys.json',
  46. help='relative path to input keys file')
  47. parser.add_argument('--quiet', action='store_true', default=False,
  48. help='do not write anything to standard output')
  49. parser.add_argument('files', nargs='+', help='input files')
  50. args = parser.parse_args()
  51. if not args.output_dir.endswith(os.path.sep):
  52. args.output_dir += os.path.sep
  53. # Read in source language .json file, which provides any values missing
  54. # in target languages' .json files.
  55. source_defs = read_json_file(os.path.join(os.curdir, args.source_lang_file))
  56. # Make sure the source file doesn't contain a newline or carriage return.
  57. for key, value in source_defs.items():
  58. if _NEWLINE_PATTERN.search(value):
  59. print('ERROR: definition of {0} in {1} contained a newline character.'.
  60. format(key, args.source_lang_file))
  61. sys.exit(1)
  62. sorted_keys = source_defs.keys()
  63. sorted_keys.sort()
  64. # Read in synonyms file, which must be output in every language.
  65. synonym_defs = read_json_file(os.path.join(
  66. os.curdir, args.source_synonym_file))
  67. synonym_text = '\n'.join(['Blockly.Msg.{0} = Blockly.Msg.{1};'.format(
  68. key, synonym_defs[key]) for key in synonym_defs])
  69. # Create each output file.
  70. for arg_file in args.files:
  71. (_, filename) = os.path.split(arg_file)
  72. target_lang = filename[:filename.index('.')]
  73. if target_lang not in ('qqq', 'keys', 'synonyms'):
  74. target_defs = read_json_file(os.path.join(os.curdir, arg_file))
  75. # Verify that keys are 'ascii'
  76. bad_keys = [key for key in target_defs if not string_is_ascii(key)]
  77. if bad_keys:
  78. print(u'These keys in {0} contain non ascii characters: {1}'.format(
  79. filename, ', '.join(bad_keys)))
  80. # If there's a '\n' or '\r', remove it and print a warning.
  81. for key, value in target_defs.items():
  82. if _NEWLINE_PATTERN.search(value):
  83. print(u'WARNING: definition of {0} in {1} contained '
  84. 'a newline character.'.
  85. format(key, arg_file))
  86. target_defs[key] = _NEWLINE_PATTERN.sub(' ', value)
  87. # Output file.
  88. outname = os.path.join(os.curdir, args.output_dir, target_lang + '.js')
  89. with codecs.open(outname, 'w', 'utf-8') as outfile:
  90. outfile.write(
  91. """// This file was automatically generated. Do not modify.
  92. 'use strict';
  93. goog.provide('Blockly.Msg.{0}');
  94. goog.require('Blockly.Msg');
  95. """.format(target_lang.replace('-', '.')))
  96. # For each key in the source language file, output the target value
  97. # if present; otherwise, output the source language value with a
  98. # warning comment.
  99. for key in sorted_keys:
  100. if key in target_defs:
  101. value = target_defs[key]
  102. comment = ''
  103. del target_defs[key]
  104. else:
  105. value = source_defs[key]
  106. comment = ' // untranslated'
  107. value = value.replace('"', '\\"')
  108. outfile.write(u'Blockly.Msg.{0} = "{1}";{2}\n'.format(
  109. key, value, comment))
  110. # Announce any keys defined only for target language.
  111. if target_defs:
  112. extra_keys = [key for key in target_defs if key not in synonym_defs]
  113. synonym_keys = [key for key in target_defs if key in synonym_defs]
  114. if not args.quiet:
  115. if extra_keys:
  116. print(u'These extra keys appeared in {0}: {1}'.format(
  117. filename, ', '.join(extra_keys)))
  118. if synonym_keys:
  119. print(u'These synonym keys appeared in {0}: {1}'.format(
  120. filename, ', '.join(synonym_keys)))
  121. outfile.write(synonym_text)
  122. if not args.quiet:
  123. print('Created {0}.'.format(outname))
  124. if __name__ == '__main__':
  125. main()