scratch-blocks 2.1.20 → 2.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,68 +0,0 @@
1
- const fs = require('fs')
2
- const path = require('path')
3
- const glob = require('glob')
4
- const assert = require('assert')
5
-
6
- // Globals
7
- const PATH_INPUT = path.resolve(__dirname, '../msg/json/*.json')
8
- const PATH_OUTPUT = path.resolve(__dirname, '../msg')
9
-
10
- let en = fs.readFileSync(path.resolve(__dirname, '../msg/json/en.json'))
11
- en = JSON.parse(en)
12
- const enKeys = Object.keys(en).sort().toString()
13
-
14
- // Check that translation is valid:
15
- // entry: array [key, translation] corresponding to a single string from <locale>.json
16
- // - messages with placeholders have the same number of placeholders
17
- // - messages must not have newlines embedded
18
- const validateEntry = function (entry) {
19
- const re = /(%\d)/g
20
- const [key, translation] = entry
21
- const enMatch = en[key].match(re)
22
- const tMatch = translation.match(re)
23
- const enCount = enMatch ? enMatch.length : 0
24
- const tCount = tMatch ? tMatch.length : 0
25
- assert.strictEqual(tCount, enCount, `${key}:${en[key]} - "${translation}" placeholder mismatch`)
26
- if (enCount > 0) {
27
- assert.notStrictEqual(tMatch, null, `${key} is missing a placeholder: ${translation}`)
28
- assert.strictEqual(
29
- tMatch.sort().toString(),
30
- enMatch.sort().toString(),
31
- `${key} is missing or has duplicate placeholders: ${translation}`,
32
- )
33
- }
34
- assert.strictEqual(translation.match(/[\n]/), null, `${key} contains a newline character ${translation}`)
35
- }
36
-
37
- const validate = function (json, name) {
38
- assert.strictEqual(Object.keys(json).sort().toString(), enKeys, `${name}: Locale json keys do not match en.json`)
39
- Object.entries(json).forEach(validateEntry)
40
- }
41
-
42
- let file = `// This file was automatically generated. Do not modify.
43
-
44
- 'use strict';
45
-
46
- goog.provide('Blockly.ScratchMsgs.allLocales');
47
-
48
- goog.require('Blockly.ScratchMsgs');
49
-
50
- `
51
-
52
- let files = glob.sync(PATH_INPUT)
53
- files.forEach(function (uri) {
54
- const name = path.parse(uri).name
55
- if (name !== 'qqq' && name !== 'synonyms') {
56
- let body = fs.readFileSync(uri)
57
- // Convert file body into an object (let this throw if invalid JSON)
58
- body = JSON.parse(body)
59
- validate(body, name)
60
- file += '\n'
61
- file += `Blockly.ScratchMsgs.locales["${name}"] =\n`
62
- file += JSON.stringify(body, null, 4)
63
- file += ';\n'
64
- }
65
- })
66
-
67
- // write combined file
68
- fs.writeFileSync(`${PATH_OUTPUT}/scratch_msgs.js`, file)
@@ -1,73 +0,0 @@
1
- #!/usr/bin/python
2
-
3
- # Consolidates duplicate key-value pairs in a JSON file.
4
- # If the same key is used with different values, no warning is given,
5
- # and there is no guarantee about which key-value pair will be output.
6
- # There is also no guarantee as to the order of the key-value pairs
7
- # output.
8
- #
9
- # Copyright 2013 Google Inc.
10
- # https://developers.google.com/blockly/
11
- #
12
- # Licensed under the Apache License, Version 2.0 (the "License");
13
- # you may not use this file except in compliance with the License.
14
- # You may obtain a copy of the License at
15
- #
16
- # http://www.apache.org/licenses/LICENSE-2.0
17
- #
18
- # Unless required by applicable law or agreed to in writing, software
19
- # distributed under the License is distributed on an "AS IS" BASIS,
20
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
- # See the License for the specific language governing permissions and
22
- # limitations under the License.
23
-
24
- import argparse
25
- import codecs
26
- import json
27
- from common import InputError
28
-
29
-
30
- def main():
31
- """Parses arguments and iterates over files.
32
-
33
- Raises:
34
- IOError: An I/O error occurred with an input or output file.
35
- InputError: Input JSON could not be parsed.
36
- """
37
-
38
- # Set up argument parser.
39
- parser = argparse.ArgumentParser(
40
- description='Removes duplicate key-value pairs from JSON files.')
41
- parser.add_argument('--suffix', default='',
42
- help='optional suffix for output files; '
43
- 'if empty, files will be changed in place')
44
- parser.add_argument('files', nargs='+', help='input files')
45
- args = parser.parse_args()
46
-
47
- # Iterate over files.
48
- for filename in args.files:
49
- # Read in json using Python libraries. This eliminates duplicates.
50
- print('Processing ' + filename + '...')
51
- try:
52
- with codecs.open(filename, 'r', 'utf-8') as infile:
53
- j = json.load(infile)
54
- except ValueError as e:
55
- print('Error reading ' + filename)
56
- raise InputError(filename, str(e))
57
-
58
- # Built up output strings as an array to make output of delimiters easier.
59
- output = []
60
- for key in j:
61
- if key != '@metadata':
62
- output.append('\t"' + key + '": "' +
63
- j[key].replace('\n', '\\n') + '"')
64
-
65
- # Output results.
66
- with codecs.open(filename + args.suffix, 'w', 'utf-8') as outfile:
67
- outfile.write('{\n')
68
- outfile.write(',\n'.join(output))
69
- outfile.write('\n}\n')
70
-
71
-
72
- if __name__ == '__main__':
73
- main()
@@ -1,54 +0,0 @@
1
- const es = require('event-stream')
2
- const fs = require('fs')
3
- const path = require('path')
4
- const assert = require('assert')
5
-
6
- // Storage object
7
- const storage = {}
8
-
9
- // File paths
10
- const PATH_INPUT = path.resolve(__dirname, '../msg/messages.js')
11
- const PATH_OUTPUT = path.resolve(__dirname, '../msg/json/en.json')
12
-
13
- // Match function
14
- const match = function (str) {
15
- if (str.indexOf('Blockly.Msg.') !== 0) return false
16
- assert.notStrictEqual(
17
- str.indexOf('";'),
18
- str.length - 2,
19
- `[${str}] uses double quoted string, should use single quotes.`,
20
- )
21
- if (str.indexOf("';") !== str.length - 2) return false
22
- return true
23
- }
24
-
25
- // Extract key and value from message definition
26
- const extract = function (str) {
27
- str = str.split('Blockly.Msg.')[1].split(' ')
28
- return {
29
- key: str[0],
30
- value: str
31
- .splice(2, str.length)
32
- .join(' ')
33
- .slice(1, -2) // strip off initial ', and ending ';
34
- .replace(/\\'/g, "'"),
35
- }
36
- }
37
-
38
- // Stream input and push each match to the storage object
39
- const stream = fs.createReadStream(PATH_INPUT)
40
- stream
41
- .pipe(es.split('\n'))
42
- .pipe(
43
- es.mapSync(function (str) {
44
- if (!match(str)) return
45
- const result = extract(str)
46
- storage[result.key] = result.value
47
- }),
48
- )
49
- .pipe(
50
- es.wait(function (err) {
51
- if (err) throw new Error(err)
52
- fs.writeFileSync(PATH_OUTPUT, JSON.stringify(storage, null, 4))
53
- }),
54
- )
@@ -1,136 +0,0 @@
1
- #!/usr/bin/python
2
-
3
- # Gives the translation status of the specified apps and languages.
4
- #
5
- # Copyright 2013 Google Inc.
6
- # https://developers.google.com/blockly/
7
- #
8
- # Licensed under the Apache License, Version 2.0 (the "License");
9
- # you may not use this file except in compliance with the License.
10
- # You may obtain a copy of the License at
11
- #
12
- # http://www.apache.org/licenses/LICENSE-2.0
13
- #
14
- # Unless required by applicable law or agreed to in writing, software
15
- # distributed under the License is distributed on an "AS IS" BASIS,
16
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
- # See the License for the specific language governing permissions and
18
- # limitations under the License.
19
-
20
- """Extracts messages from .js files into .json files for translation.
21
-
22
- Specifically, lines with the following formats are extracted:
23
-
24
- /// Here is a description of the following message.
25
- Blockly.SOME_KEY = 'Some value';
26
-
27
- Adjacent "///" lines are concatenated.
28
-
29
- There are two output files, each of which is proper JSON. For each key, the
30
- file en.json would get an entry of the form:
31
-
32
- "Blockly.SOME_KEY", "Some value",
33
-
34
- The file qqq.json would get:
35
-
36
- "Blockly.SOME_KEY", "Here is a description of the following message.",
37
-
38
- Commas would of course be omitted for the final entry of each value.
39
-
40
- @author Ellen Spertus (ellen.spertus@gmail.com)
41
- """
42
-
43
- import argparse
44
- import codecs
45
- import json
46
- import os
47
- import re
48
- from common import write_files
49
-
50
-
51
- _INPUT_DEF_PATTERN = re.compile("""Blockly.Msg.(\w*)\s*=\s*'(.*)';?\r?$""")
52
-
53
- _INPUT_SYN_PATTERN = re.compile(
54
- """Blockly.Msg.(\w*)\s*=\s*Blockly.Msg.(\w*);""")
55
-
56
- _CONSTANT_DESCRIPTION_PATTERN = re.compile(
57
- """{{Notranslate}}""", re.IGNORECASE)
58
-
59
- def main():
60
- # Set up argument parser.
61
- parser = argparse.ArgumentParser(description='Create translation files.')
62
- parser.add_argument(
63
- '--author',
64
- default='Ellen Spertus <ellen.spertus@gmail.com>',
65
- help='name and email address of contact for translators')
66
- parser.add_argument('--lang', default='en',
67
- help='ISO 639-1 source language code')
68
- parser.add_argument('--output_dir', default='json',
69
- help='relative directory for output files')
70
- parser.add_argument('--input_file', default='messages.js',
71
- help='input file')
72
- parser.add_argument('--quiet', action='store_true', default=False,
73
- help='only display warnings, not routine info')
74
- args = parser.parse_args()
75
- if (not args.output_dir.endswith(os.path.sep)):
76
- args.output_dir += os.path.sep
77
-
78
- # Read and parse input file.
79
- results = []
80
- synonyms = {}
81
- constants = {} # Values that are constant across all languages.
82
- description = ''
83
- infile = codecs.open(args.input_file, 'r', 'utf-8')
84
- for line in infile:
85
- if line.startswith('///'):
86
- if description:
87
- description = description + ' ' + line[3:].strip()
88
- else:
89
- description = line[3:].strip()
90
- else:
91
- match = _INPUT_DEF_PATTERN.match(line)
92
- if match:
93
- key = match.group(1)
94
- value = match.group(2).replace("\\'", "'")
95
- if not description:
96
- print('Warning: No description for ' + result['meaning'])
97
- if (description and _CONSTANT_DESCRIPTION_PATTERN.search(description)):
98
- constants[key] = value
99
- else:
100
- result = {}
101
- result['meaning'] = key
102
- result['source'] = value
103
- result['description'] = description
104
- results.append(result)
105
- description = ''
106
- else:
107
- match = _INPUT_SYN_PATTERN.match(line)
108
- if match:
109
- if description:
110
- print('Warning: Description preceding definition of synonym {0}.'.
111
- format(match.group(1)))
112
- description = ''
113
- synonyms[match.group(1)] = match.group(2)
114
- infile.close()
115
-
116
- # Create <lang_file>.json, keys.json, and qqq.json.
117
- write_files(args.author, args.lang, args.output_dir, results, False)
118
-
119
- # Create synonyms.json.
120
- synonym_file_name = os.path.join(os.curdir, args.output_dir, 'synonyms.json')
121
- with open(synonym_file_name, 'w') as outfile:
122
- json.dump(synonyms, outfile)
123
- if not args.quiet:
124
- print("Wrote {0} synonym pairs to {1}.".format(
125
- len(synonyms), synonym_file_name))
126
-
127
- # Create constants.json
128
- constants_file_name = os.path.join(os.curdir, args.output_dir, 'constants.json')
129
- with open(constants_file_name, 'w') as outfile:
130
- json.dump(constants, outfile)
131
- if not args.quiet:
132
- print("Wrote {0} constant pairs to {1}.".format(
133
- len(constants), synonym_file_name))
134
-
135
- if __name__ == '__main__':
136
- main()
@@ -1,52 +0,0 @@
1
- const async = require('async')
2
- const fs = require('fs')
3
- const path = require('path')
4
- const glob = require('glob')
5
-
6
- // Globals
7
- const PATH_INPUT = path.resolve(__dirname, '../msg/json/en.json')
8
- // If you want to generate js files for other languages, comment out the line above,
9
- // and use the one below instead.
10
- // const PATH_INPUT = path.resolve(__dirname, '../msg/json/*.json');
11
- const PATH_OUTPUT = path.resolve(__dirname, '../msg/js')
12
- const CONCURRENCY_LIMIT = 4
13
-
14
- // Processing task
15
- const work = function (uri, callback) {
16
- fs.readFile(uri, function (err, body) {
17
- const name = path.parse(uri).name
18
- if (err) return callback(err)
19
-
20
- // Convert file body into an object (let this throw if invalid JSON)
21
- body = JSON.parse(body)
22
-
23
- // File storage object and preamble
24
- let file = ''
25
- file += '// This file was automatically generated. Do not modify.\n'
26
- file += '\n'
27
- file += "'use strict';\n"
28
- file += '\n'
29
- file += `goog.provide(\'Blockly.Msg.${name}\');\n`
30
- file += "goog.require('Blockly.Msg');\n"
31
- file += '\n'
32
-
33
- // Iterate over object and build up file
34
- for (let i in body) {
35
- file += `Blockly.Msg["${i}"] = "${body[i].replace(/"/g, '\\"')}";\n`
36
- }
37
-
38
- // Write file to disk
39
- fs.writeFile(`${PATH_OUTPUT}/${name}.js`, file, callback)
40
- })
41
- }
42
-
43
- // Create async processing queue
44
- const q = async.queue(work, CONCURRENCY_LIMIT)
45
-
46
- // Handle errors
47
- q.error = function (err) {
48
- throw new Error(err)
49
- }
50
-
51
- // Get all JSON files in input directory and add to queue
52
- q.push(glob.sync(PATH_INPUT))
@@ -1,185 +0,0 @@
1
- #!/usr/bin/python
2
-
3
- # Converts .json files into .js files for use within Blockly apps.
4
- #
5
- # Copyright 2013 Google Inc.
6
- # https://developers.google.com/blockly/
7
- #
8
- # Licensed under the Apache License, Version 2.0 (the "License");
9
- # you may not use this file except in compliance with the License.
10
- # You may obtain a copy of the License at
11
- #
12
- # http://www.apache.org/licenses/LICENSE-2.0
13
- #
14
- # Unless required by applicable law or agreed to in writing, software
15
- # distributed under the License is distributed on an "AS IS" BASIS,
16
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
- # See the License for the specific language governing permissions and
18
- # limitations under the License.
19
-
20
- import argparse
21
- import codecs # for codecs.open(..., 'utf-8')
22
- import glob
23
- import json # for json.load()
24
- import os # for os.path()
25
- import subprocess # for subprocess.check_call()
26
- from common import InputError
27
- from common import read_json_file
28
-
29
-
30
- # Store parsed command-line arguments in global variable.
31
- args = None
32
-
33
-
34
- def _create_xlf(target_lang):
35
- """Creates a <target_lang>.xlf file for Soy.
36
-
37
- Args:
38
- target_lang: The ISO 639 language code for the target language.
39
- This is used in the name of the file and in the metadata.
40
-
41
- Returns:
42
- A pointer to a file to which the metadata has been written.
43
-
44
- Raises:
45
- IOError: An error occurred while opening or writing the file.
46
- """
47
- filename = os.path.join(os.curdir, args.output_dir, target_lang + '.xlf')
48
- out_file = codecs.open(filename, 'w', 'utf-8')
49
- out_file.write("""<?xml version="1.0" encoding="UTF-8"?>
50
- <xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
51
- <file original="SoyMsgBundle"
52
- datatype="x-soy-msg-bundle"
53
- xml:space="preserve"
54
- source-language="{0}"
55
- target-language="{1}">
56
- <body>""".format(args.source_lang, target_lang))
57
- return out_file
58
-
59
-
60
- def _close_xlf(xlf_file):
61
- """Closes a <target_lang>.xlf file created with create_xlf().
62
-
63
- This includes writing the terminating XML.
64
-
65
- Args:
66
- xlf_file: A pointer to a file created by _create_xlf().
67
-
68
- Raises:
69
- IOError: An error occurred while writing to or closing the file.
70
- """
71
- xlf_file.write("""
72
- </body>
73
- </file>
74
- </xliff>
75
- """)
76
- xlf_file.close()
77
-
78
-
79
- def _process_file(path_to_json, target_lang, key_dict):
80
- """Creates an .xlf file corresponding to the specified .json input file.
81
-
82
- The name of the input file must be target_lang followed by '.json'.
83
- The name of the output file will be target_lang followed by '.js'.
84
-
85
- Args:
86
- path_to_json: Path to the directory of xx.json files.
87
- target_lang: A IETF language code (RFC 4646), such as 'es' or 'pt-br'.
88
- key_dict: Dictionary mapping Blockly keys (e.g., Maze.turnLeft) to
89
- Closure keys (hash numbers).
90
-
91
- Raises:
92
- IOError: An I/O error occurred with an input or output file.
93
- InputError: Input JSON could not be parsed.
94
- KeyError: Key found in input file but not in key file.
95
- """
96
- keyfile = os.path.join(path_to_json, target_lang + '.json')
97
- j = read_json_file(keyfile)
98
- out_file = _create_xlf(target_lang)
99
- for key in j:
100
- if key != '@metadata':
101
- try:
102
- identifier = key_dict[key]
103
- except KeyError as e:
104
- print('Key "%s" is in %s but not in %s' %
105
- (key, keyfile, args.key_file))
106
- raise e
107
- target = j.get(key)
108
- out_file.write(u"""
109
- <trans-unit id="{0}" datatype="html">
110
- <target>{1}</target>
111
- </trans-unit>""".format(identifier, target))
112
- _close_xlf(out_file)
113
-
114
-
115
- def main():
116
- """Parses arguments and iterates over files."""
117
-
118
- # Set up argument parser.
119
- parser = argparse.ArgumentParser(description='Convert JSON files to JS.')
120
- parser.add_argument('--source_lang', default='en',
121
- help='ISO 639-1 source language code')
122
- parser.add_argument('--output_dir', default='generated',
123
- help='relative directory for output files')
124
- parser.add_argument('--key_file', default='json' + os.path.sep + 'keys.json',
125
- help='relative path to input keys file')
126
- parser.add_argument('--template', default='template.soy')
127
- parser.add_argument('--path_to_jar',
128
- default='..' + os.path.sep + 'apps' + os.path.sep
129
- + '_soy',
130
- help='relative path from working directory to '
131
- 'SoyToJsSrcCompiler.jar')
132
- parser.add_argument('files', nargs='+', help='input files')
133
-
134
- # Initialize global variables.
135
- global args
136
- args = parser.parse_args()
137
-
138
- # Make sure output_dir ends with slash.
139
- if (not args.output_dir.endswith(os.path.sep)):
140
- args.output_dir += os.path.sep
141
-
142
- # Read in keys.json, mapping descriptions (e.g., Maze.turnLeft) to
143
- # Closure keys (long hash numbers).
144
- key_file = open(args.key_file)
145
- key_dict = json.load(key_file)
146
- key_file.close()
147
-
148
- # Process each input file.
149
- print('Creating .xlf files...')
150
- processed_langs = []
151
- if len(args.files) == 1:
152
- # Windows does not expand globs automatically.
153
- args.files = glob.glob(args.files[0])
154
- for arg_file in args.files:
155
- (path_to_json, filename) = os.path.split(arg_file)
156
- if not filename.endswith('.json'):
157
- raise InputError(filename, 'filenames must end with ".json"')
158
- target_lang = filename[:filename.index('.')]
159
- if not target_lang in ('qqq', 'keys'):
160
- processed_langs.append(target_lang)
161
- _process_file(path_to_json, target_lang, key_dict)
162
-
163
- # Output command line for Closure compiler.
164
- if processed_langs:
165
- print('Creating .js files...')
166
- processed_lang_list = ','.join(processed_langs)
167
- subprocess.check_call([
168
- 'java',
169
- '-jar', os.path.join(args.path_to_jar, 'SoyToJsSrcCompiler.jar'),
170
- '--locales', processed_lang_list,
171
- '--messageFilePathFormat', args.output_dir + '{LOCALE}.xlf',
172
- '--outputPathFormat', args.output_dir + '{LOCALE}.js',
173
- '--srcs', args.template])
174
- if len(processed_langs) == 1:
175
- print('Created ' + processed_lang_list + '.js in ' + args.output_dir)
176
- else:
177
- print('Created {' + processed_lang_list + '}.js in ' + args.output_dir)
178
-
179
- for lang in processed_langs:
180
- os.remove(args.output_dir + lang + '.xlf')
181
- print('Removed .xlf files.')
182
-
183
-
184
- if __name__ == '__main__':
185
- main()
@@ -1,110 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * @fileoverview
5
- * Script to pull translations for blocks from transifex and generate the scratch_msgs file.
6
- * Expects that the project and resource have already been defined in Transifex, and that
7
- * the person running the script has the the TX_TOKEN environment variable set to an api
8
- * token that has developer access.
9
- */
10
-
11
- const usage = `
12
- Pull supported language translations from Transifex. Usage:
13
- node sync_tx_translations.js
14
- NOTE: TX_TOKEN environment variable needs to be set with a Transifex API token. See
15
- the Localization page on the GUI wiki for information about setting up Transifex.
16
- `
17
- // Fail immediately if the TX_TOKEN is not defined
18
- if (!process.env.TX_TOKEN || process.argv.length !== 2) {
19
- process.stdout.write(usage)
20
- process.exit(1)
21
- }
22
-
23
- const fs = require('fs')
24
- const path = require('path')
25
- const assert = require('assert')
26
- const locales = require('scratch-l10n').default
27
- const { txPull } = require('scratch-l10n/lib/transifex.js')
28
-
29
- // Globals
30
- const PATH_OUTPUT = path.resolve(__dirname, '../msg')
31
- const PROJECT = 'scratch-editor'
32
- const RESOURCE = 'blocks'
33
- const MODE = 'reviewed'
34
-
35
- let en = fs.readFileSync(path.resolve(__dirname, '../msg/json/en.json'))
36
- en = JSON.parse(en)
37
- const enKeys = Object.keys(en).sort().toString()
38
-
39
- // Check that translation is valid:
40
- // entry: array [key, translation] corresponding to a single string from <locale>.json
41
- // - messages with placeholders have the same number of placeholders
42
- // - messages must not have newlines embedded
43
- const validateEntry = function (entry) {
44
- const re = /(%\d)/g
45
- const [key, translation] = entry
46
- const enMatch = en[key].match(re)
47
- const tMatch = translation.match(re)
48
- const enCount = enMatch ? enMatch.length : 0
49
- const tCount = tMatch ? tMatch.length : 0
50
- assert.strictEqual(tCount, enCount, `${key}:${en[key]} - "${translation}" placeholder mismatch`)
51
- if (enCount > 0) {
52
- assert.notStrictEqual(tMatch, null, `${key} is missing a placeholder: ${translation}`)
53
- assert.strictEqual(
54
- tMatch.sort().toString(),
55
- enMatch.sort().toString(),
56
- `${key} is missing or has duplicate placeholders: ${translation}`,
57
- )
58
- }
59
- assert.strictEqual(translation.match(/[\n]/), null, `${key} contains a newline character ${translation}`)
60
- }
61
-
62
- const validate = function (json, name) {
63
- assert.strictEqual(Object.keys(json).sort().toString(), enKeys, `${name}: Locale json keys do not match en.json`)
64
- Object.entries(json).forEach(validateEntry)
65
- }
66
-
67
- let file = `// This file was automatically generated. Do not modify.
68
-
69
- 'use strict';
70
-
71
- goog.provide('Blockly.ScratchMsgs.allLocales');
72
-
73
- goog.require('Blockly.ScratchMsgs');
74
-
75
- `
76
-
77
- let localeMap = {
78
- 'aa-dj': 'aa_DJ',
79
- 'es-419': 'es_419',
80
- 'pt-br': 'pt_BR',
81
- 'zh-cn': 'zh_CN',
82
- 'zh-tw': 'zh_TW',
83
- }
84
-
85
- const getLocaleData = async function (locale) {
86
- let txLocale = localeMap[locale] || locale
87
- const data = await txPull(PROJECT, RESOURCE, txLocale, MODE)
88
- return {
89
- locale: locale,
90
- translations: data,
91
- }
92
- }
93
-
94
- Promise.all(Object.keys(locales).map(getLocaleData))
95
- .then(function (values) {
96
- values.forEach(function (translation) {
97
- validate(translation.translations, translation.locale)
98
- file += '\n'
99
- file += `Blockly.ScratchMsgs.locales["${translation.locale}"] =\n`
100
- file += JSON.stringify(translation.translations, null, 4)
101
- file += ';\n'
102
- })
103
- file += '// End of combined translations\n'
104
- // write combined file
105
- fs.writeFileSync(`${PATH_OUTPUT}/scratch_msgs.js`, file)
106
- })
107
- .catch((err) => {
108
- console.error(err)
109
- process.exit(1)
110
- })