@@ -781,32 +781,49 @@ private void injectExternalLuaFiles(File script) {
781781 } catch (FileNotFoundException e ) {
782782 throw new RuntimeException ("Cannot get build dir" , e );
783783 }
784- if (luaDir .exists ()) {
785- File [] children = luaDir .listFiles ();
786- if (children != null ) {
787- Arrays .stream (children ).forEach (child -> {
788- try {
789- byte [] bytes = java .nio .file .Files .readAllBytes (child .toPath ());
790- if (child .getName ().startsWith ("pre_" )) {
791- byte [] existingBytes = java .nio .file .Files .readAllBytes (script .toPath ());
792- java .nio .file .Files .write (
793- script .toPath (),
794- bytes );
795- java .nio .file .Files .write (
796- script .toPath (),
797- existingBytes ,
798- StandardOpenOption .APPEND );
799- } else {
800- java .nio .file .Files .write (
801- script .toPath (),
802- bytes ,
803- StandardOpenOption .APPEND );
804- }
805- } catch (IOException e ) {
806- throw new RuntimeException (e );
807- }
808- });
784+ if (!luaDir .exists ()) {
785+ return ;
786+ }
787+
788+ try (var fileStream = java .nio .file .Files .walk (luaDir .toPath ())) {
789+ List <Path > luaFiles = fileStream
790+ .filter (java .nio .file .Files ::isRegularFile )
791+ .sorted (Comparator .comparing (path -> {
792+ Path relative = luaDir .toPath ().relativize (path );
793+ return relative .toString ().replace ('\\' , '/' ).toLowerCase (Locale .ROOT );
794+ }))
795+ .collect (Collectors .toList ());
796+
797+ if (luaFiles .isEmpty ()) {
798+ return ;
799+ }
800+
801+ List <byte []> preChunks = new ArrayList <>();
802+ List <byte []> postChunks = new ArrayList <>();
803+ for (Path luaFile : luaFiles ) {
804+ byte [] bytes = java .nio .file .Files .readAllBytes (luaFile );
805+ String fileName = luaFile .getFileName ().toString ();
806+ if (fileName .startsWith ("pre_" )) {
807+ preChunks .add (bytes );
808+ } else {
809+ postChunks .add (bytes );
810+ }
811+ }
812+
813+ if (!preChunks .isEmpty ()) {
814+ byte [] existingBytes = java .nio .file .Files .readAllBytes (script .toPath ());
815+ java .nio .file .Files .write (script .toPath (), new byte [0 ]);
816+ for (byte [] preChunk : preChunks ) {
817+ java .nio .file .Files .write (script .toPath (), preChunk , StandardOpenOption .APPEND );
818+ }
819+ java .nio .file .Files .write (script .toPath (), existingBytes , StandardOpenOption .APPEND );
809820 }
821+
822+ for (byte [] postChunk : postChunks ) {
823+ java .nio .file .Files .write (script .toPath (), postChunk , StandardOpenOption .APPEND );
824+ }
825+ } catch (IOException e ) {
826+ throw new RuntimeException (e );
810827 }
811828 }
812829
0 commit comments