|
| 1 | +from __future__ import absolute_import, print_function |
| 2 | + |
| 3 | +import os |
| 4 | +import re |
| 5 | + |
| 6 | +LOCALES_DIR = 'src/sentry/data/error-locale' |
| 7 | + |
| 8 | +translations_lookup_table = [] |
| 9 | +target_locale = {} |
| 10 | + |
| 11 | +for locale in os.listdir(LOCALES_DIR): |
| 12 | + fn = os.path.join(LOCALES_DIR, locale) |
| 13 | + if not os.path.isfile(fn): |
| 14 | + continue |
| 15 | + |
| 16 | + with open(fn) as f: |
| 17 | + for line in f: |
| 18 | + key, translation = line.split(',', 1) |
| 19 | + translation = translation.strip() |
| 20 | + |
| 21 | + if 'en-US' in locale: |
| 22 | + target_locale[key] = translation |
| 23 | + else: |
| 24 | + translation_regexp = re.escape(translation) |
| 25 | + # Some generic errors are substrings of more detailed ones, so we need an |
| 26 | + # exact match |
| 27 | + translation_regexp = '^' + \ |
| 28 | + translation_regexp.replace( |
| 29 | + '\%s', '(?P<format_string_data>[a-zA-Z0-9-_\$]+)') + '$' |
| 30 | + translation_regexp = re.compile(translation_regexp) |
| 31 | + translations_lookup_table.append((translation_regexp, key)) |
| 32 | + |
| 33 | + |
| 34 | +def find_translation(message): |
| 35 | + for translation in translations_lookup_table: |
| 36 | + translation_regexp, key = translation |
| 37 | + match = translation_regexp.match(message) |
| 38 | + |
| 39 | + if match is not None: |
| 40 | + format_string_data = match.groupdict().get('format_string_data') |
| 41 | + |
| 42 | + if format_string_data is None: |
| 43 | + return [key, None] |
| 44 | + else: |
| 45 | + return [key, format_string_data] |
| 46 | + |
| 47 | + return [None, None] |
| 48 | + |
| 49 | + |
| 50 | +def format_message(message, data): |
| 51 | + return message.replace('%s', data) |
| 52 | + |
| 53 | + |
| 54 | +def translate_message(original_message): |
| 55 | + original_message = original_message.strip() |
| 56 | + translation, format_string_data = find_translation(original_message) |
| 57 | + |
| 58 | + if translation is None: |
| 59 | + return original_message |
| 60 | + else: |
| 61 | + translated_message = target_locale.get(translation, original_message) |
| 62 | + |
| 63 | + if format_string_data is None: |
| 64 | + return translated_message |
| 65 | + else: |
| 66 | + return format_message(translated_message, format_string_data) |
| 67 | + |
| 68 | + |
| 69 | +def translate_exception(data): |
| 70 | + type, message = data['sentry.interfaces.Message']['message'].split(':', 1) |
| 71 | + |
| 72 | + print('Input: ' + message) |
| 73 | + print('Output: ' + translate_message(message)) |
| 74 | + data['sentry.interfaces.Message']['message'] = type + ': ' + translate_message(message) |
| 75 | + |
| 76 | + for entry in data['sentry.interfaces.Exception']['values']: |
| 77 | + print('Input: ' + entry['value']) |
| 78 | + print('Output: ' + translate_message(entry['value'])) |
| 79 | + entry['value'] = translate_message(entry['value']) |
0 commit comments