Skip to content

Commit d539534

Browse files
committed
Cleanup tools/file_packager.py and its output. NFC
- Use enumerate() to avoid a counter - (mostly) Fix indentation of generated JS
1 parent 17cbd29 commit d539534

File tree

1 file changed

+81
-103
lines changed

1 file changed

+81
-103
lines changed

tools/file_packager.py

Lines changed: 81 additions & 103 deletions
Original file line numberDiff line numberDiff line change
@@ -282,8 +282,7 @@ def main():
282282
# standalone calls
283283
if not from_emcc:
284284
ret = '''
285-
var Module = typeof %(EXPORT_NAME)s !== 'undefined' ? %(EXPORT_NAME)s : {};
286-
''' % {"EXPORT_NAME": export_name}
285+
var Module = typeof %(EXPORT_NAME)s !== 'undefined' ? %(EXPORT_NAME)s : {};\n''' % {"EXPORT_NAME": export_name}
287286

288287
ret += '''
289288
if (!Module.expectedDataFileDownloads) {
@@ -294,14 +293,12 @@ def main():
294293
// When running as a pthread, FS operations are proxied to the main thread, so we don't need to
295294
// fetch the .data bundle on the worker
296295
if (Module['ENVIRONMENT_IS_PTHREAD']) return;
297-
var loadPackage = function(metadata) {
298-
'''
296+
var loadPackage = function(metadata) {\n'''
299297

300298
code = '''
301299
function assert(check, msg) {
302300
if (!check) throw msg + new Error().stack;
303-
}
304-
'''
301+
}\n'''
305302

306303
for file_ in data_files:
307304
if not should_ignore(file_['srcpath']):
@@ -428,62 +425,57 @@ def was_seen(name):
428425
}, false, true); // canOwn this data in the filesystem, it is a slide into the heap that will never change
429426
'''
430427
create_data = '''
431-
Module['FS_createDataFile'](this.name, null, byteArray, true, true, true); // canOwn this data in the filesystem, it is a slide into the heap that will never change
428+
// canOwn this data in the filesystem, it is a slide into the heap that will never change
429+
Module['FS_createDataFile'](this.name, null, byteArray, true, true, true);
432430
Module['removeRunDependency']('fp ' + that.name);
433431
'''
434432

435433
if not lz4:
436434
# Data requests - for getting a block of data out of the big archive - have
437435
# a similar API to XHRs
438436
code += '''
439-
/** @constructor */
440-
function DataRequest(start, end, audio) {
441-
this.start = start;
442-
this.end = end;
443-
this.audio = audio;
444-
}
445-
DataRequest.prototype = {
446-
requests: {},
447-
open: function(mode, name) {
448-
this.name = name;
449-
this.requests[name] = this;
450-
Module['addRunDependency']('fp ' + this.name);
451-
},
452-
send: function() {},
453-
onload: function() {
454-
var byteArray = this.byteArray.subarray(this.start, this.end);
455-
this.finish(byteArray);
456-
},
457-
finish: function(byteArray) {
458-
var that = this;
459-
%s
460-
this.requests[this.name] = null;
461-
}
462-
};
437+
/** @constructor */
438+
function DataRequest(start, end, audio) {
439+
this.start = start;
440+
this.end = end;
441+
this.audio = audio;
442+
}
443+
DataRequest.prototype = {
444+
requests: {},
445+
open: function(mode, name) {
446+
this.name = name;
447+
this.requests[name] = this;
448+
Module['addRunDependency']('fp ' + this.name);
449+
},
450+
send: function() {},
451+
onload: function() {
452+
var byteArray = this.byteArray.subarray(this.start, this.end);
453+
this.finish(byteArray);
454+
},
455+
finish: function(byteArray) {
456+
var that = this;
463457
%s
464-
''' % (create_preloaded if use_preload_plugins else create_data, '''
465-
var files = metadata['files'];
466-
for (var i = 0; i < files.length; ++i) {
467-
new DataRequest(files[i]['start'], files[i]['end'], files[i]['audio'] || 0).open('GET', files[i]['filename']);
468-
}
469-
''')
458+
this.requests[this.name] = null;
459+
}
460+
};
470461
471-
counter = 0
472-
for file_ in data_files:
462+
var files = metadata['files'];
463+
for (var i = 0; i < files.length; ++i) {
464+
new DataRequest(files[i]['start'], files[i]['end'], files[i]['audio'] || 0).open('GET', files[i]['filename']);
465+
}\n''' % (create_preloaded if use_preload_plugins else create_data)
466+
467+
for (counter, file_) in enumerate(data_files):
473468
filename = file_['dstpath']
474469
dirname = os.path.dirname(filename)
475470
basename = os.path.basename(filename)
476471
if file_['mode'] == 'embed':
477472
# Embed
478473
data = base64_encode(utils.read_binary(file_['srcpath']))
479-
code += '''var fileData%d = '%s';\n''' % (counter, data)
480-
code += ('''Module['FS_createDataFile']('%s', '%s', decodeBase64(fileData%d), true, true, false);\n'''
474+
code += " var fileData%d = '%s';\n" % (counter, data)
475+
code += (" Module['FS_createDataFile']('%s', '%s', decodeBase64(fileData%d), true, true, false);\n"
481476
% (dirname, basename, counter))
482-
counter += 1
483477
elif file_['mode'] == 'preload':
484478
# Preload
485-
counter += 1
486-
487479
metadata_el = {
488480
'filename': file_['dstpath'],
489481
'start': file_['data_start'],
@@ -501,14 +493,12 @@ def was_seen(name):
501493
# Get the big archive and split it up
502494
use_data = '''
503495
// Reuse the bytearray from the XHR as the source for file reads.
504-
DataRequest.prototype.byteArray = byteArray;
505-
'''
496+
DataRequest.prototype.byteArray = byteArray;\n'''
506497
use_data += '''
507-
var files = metadata['files'];
508-
for (var i = 0; i < files.length; ++i) {
509-
DataRequest.prototype.requests[files[i].filename].onload();
510-
}
511-
'''
498+
var files = metadata['files'];
499+
for (var i = 0; i < files.length; ++i) {
500+
DataRequest.prototype.requests[files[i].filename].onload();
501+
}\n'''
512502
use_data += (" Module['removeRunDependency']('datafile_%s');\n"
513503
% js_manipulation.escape_for_js_string(data_target))
514504

@@ -723,7 +713,7 @@ def was_seen(name):
723713
# add Node.js support code, if necessary
724714
node_support_code = ''
725715
if support_node:
726-
node_support_code = r'''
716+
node_support_code = '''
727717
if (typeof process === 'object' && typeof process.versions === 'object' && typeof process.versions.node === 'string') {
728718
require('fs').readFile(packageName, function(err, contents) {
729719
if (err) {
@@ -733,9 +723,8 @@ def was_seen(name):
733723
}
734724
});
735725
return;
736-
}
737-
'''
738-
ret += r'''
726+
}\n'''
727+
ret += '''
739728
function fetchRemotePackage(packageName, packageSize, callback, errback) {
740729
%(node_support_code)s
741730
var xhr = new XMLHttpRequest();
@@ -787,28 +776,25 @@ def was_seen(name):
787776
788777
function handleError(error) {
789778
console.error('package error:', error);
790-
};
791-
''' % {'node_support_code': node_support_code}
779+
};\n''' % {'node_support_code': node_support_code}
792780

793-
code += r'''
781+
code += '''
794782
function processPackageData(arrayBuffer) {
795783
assert(arrayBuffer, 'Loading data file failed.');
796784
assert(arrayBuffer instanceof ArrayBuffer, 'bad input to processPackageData');
797785
var byteArray = new Uint8Array(arrayBuffer);
798786
var curr;
799787
%s
800788
};
801-
Module['addRunDependency']('datafile_%s');
802-
''' % (use_data, js_manipulation.escape_for_js_string(data_target))
789+
Module['addRunDependency']('datafile_%s');\n''' % (use_data, js_manipulation.escape_for_js_string(data_target))
803790
# use basename because from the browser's point of view,
804791
# we need to find the datafile in the same dir as the html file
805792

806-
code += r'''
807-
if (!Module.preloadResults) Module.preloadResults = {};
808-
'''
793+
code += '''
794+
if (!Module.preloadResults) Module.preloadResults = {};\n'''
809795

810796
if use_preload_cache:
811-
code += r'''
797+
code += '''
812798
function preloadFallback(error) {
813799
console.error(error);
814800
console.error('falling back to default preload behavior');
@@ -838,40 +824,36 @@ def was_seen(name):
838824
}
839825
, preloadFallback);
840826
841-
if (Module['setStatus']) Module['setStatus']('Downloading...');
842-
'''
827+
if (Module['setStatus']) Module['setStatus']('Downloading...');\n'''
843828
else:
844829
# Not using preload cache, so we might as well start the xhr ASAP,
845830
# potentially before JS parsing of the main codebase if it's after us.
846831
# Only tricky bit is the fetch is async, but also when runWithFS is called
847832
# is async, so we handle both orderings.
848-
ret += r'''
849-
var fetchedCallback = null;
850-
var fetched = Module['getPreloadedPackage'] ? Module['getPreloadedPackage'](REMOTE_PACKAGE_NAME, REMOTE_PACKAGE_SIZE) : null;
851-
852-
if (!fetched) fetchRemotePackage(REMOTE_PACKAGE_NAME, REMOTE_PACKAGE_SIZE, function(data) {
853-
if (fetchedCallback) {
854-
fetchedCallback(data);
855-
fetchedCallback = null;
856-
} else {
857-
fetched = data;
858-
}
859-
}, handleError);
860-
'''
861-
862-
code += r'''
863-
Module.preloadResults[PACKAGE_NAME] = {fromCache: false};
864-
if (fetched) {
865-
processPackageData(fetched);
866-
fetched = null;
833+
ret += '''
834+
var fetchedCallback = null;
835+
var fetched = Module['getPreloadedPackage'] ? Module['getPreloadedPackage'](REMOTE_PACKAGE_NAME, REMOTE_PACKAGE_SIZE) : null;
836+
837+
if (!fetched) fetchRemotePackage(REMOTE_PACKAGE_NAME, REMOTE_PACKAGE_SIZE, function(data) {
838+
if (fetchedCallback) {
839+
fetchedCallback(data);
840+
fetchedCallback = null;
867841
} else {
868-
fetchedCallback = processPackageData;
842+
fetched = data;
869843
}
870-
'''
844+
}, handleError);\n'''
845+
846+
code += '''
847+
Module.preloadResults[PACKAGE_NAME] = {fromCache: false};
848+
if (fetched) {
849+
processPackageData(fetched);
850+
fetched = null;
851+
} else {
852+
fetchedCallback = processPackageData;
853+
}\n'''
871854

872855
ret += '''
873-
function runWithFS() {
874-
'''
856+
function runWithFS() {\n'''
875857
ret += code
876858
ret += '''
877859
}
@@ -880,15 +862,14 @@ def was_seen(name):
880862
} else {
881863
if (!Module['preRun']) Module['preRun'] = [];
882864
Module["preRun"].push(runWithFS); // FS is not initialized yet, wait for it
883-
}
884-
'''
865+
}\n'''
885866

886867
if separate_metadata:
887868
_metadata_template = '''
888869
Module['removeRunDependency']('%(metadata_file)s');
889-
}
870+
}
890871
891-
function runMetaWithFS() {
872+
function runMetaWithFS() {
892873
Module['addRunDependency']('%(metadata_file)s');
893874
var REMOTE_METADATA_NAME = Module['locateFile'] ? Module['locateFile']('%(metadata_file)s', '') : '%(metadata_file)s';
894875
var xhr = new XMLHttpRequest();
@@ -900,25 +881,22 @@ def was_seen(name):
900881
xhr.open('GET', REMOTE_METADATA_NAME, true);
901882
xhr.overrideMimeType('application/json');
902883
xhr.send(null);
903-
}
884+
}
904885
905-
if (Module['calledRun']) {
886+
if (Module['calledRun']) {
906887
runMetaWithFS();
907-
} else {
888+
} else {
908889
if (!Module['preRun']) Module['preRun'] = [];
909890
Module["preRun"].push(runMetaWithFS);
910-
}
911-
''' % {'metadata_file': os.path.basename(jsoutput + '.metadata')}
891+
}\n''' % {'metadata_file': os.path.basename(jsoutput + '.metadata')}
912892

913893
else:
914894
_metadata_template = '''
915-
}
916-
loadPackage(%s);
917-
''' % json.dumps(metadata)
895+
}
896+
loadPackage(%s);\n''' % json.dumps(metadata)
918897

919898
ret += '''%s
920-
})();
921-
''' % _metadata_template
899+
})();\n''' % _metadata_template
922900

923901
if force or len(data_files):
924902
if jsoutput is None:

0 commit comments

Comments
 (0)