forked from topitbopit/RedlinePack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpacker.js
424 lines (325 loc) · 16.6 KB
/
packer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/* RedlinePack v1.1.1 */
/* Written by topit for Redline */
// Warning: I barely know any JS - let me know if anything can be done better
const ver = 'v1.1.1'
const fs = require( 'fs' )
const path = require( 'path' )
const luamin = require( 'luamin' )
let config // setting config
if ( fs.existsSync( 'settings.json' ) ) {
config = JSON.parse( fs.readFileSync( 'settings.json' ).toString() )
} else {
config = {
// keywords
"keywordSingle": "IMPORT",
"keywordDirectory": "IMPORT_DIR",
"keywordMulti": "IMPORT_MULTI",
// tab spacing
"tabLength": 4, // how many spaces each "tab" is
"smartIndents": true, // tries to figure out the current indent level and indents the packed output accordingly
// extra
"fileComments": true, // includes comments in the output displaying original file locations
"redundantImporting": false, // lets you import the same file multiple times; very risky, lets you infinitely import the same file!
"packerWatermark": true, // adds a packer watermark
"verboseLogs": true,
"minify": false,
// input / output
"outputFile": "compiled.lua",
"inputFile": "src/main.lua"
}
fs.writeFileSync( 'settings.json', JSON.stringify( config ) )
}
// console colors
// i could use chalk but this is less effort 😈
let tags = {
'reset': '\x1b[0m',
'error': `\x1b[38;5;250m[\x1b[38;5;197mERROR\x1b[38;5;250m]\x1b[38;5;161m `,
'warn': `\x1b[38;5;250m[\x1b[38;5;220mWARNING\x1b[38;5;250m]\x1b[38;5;229m `,
'info': `\x1b[38;5;250m[\x1b[38;5;231mINFO\x1b[38;5;250m]\x1b[0m `,
'success': `\x1b[38;5;250m[\x1b[38;5;120mSUCCESS\x1b[38;5;250m]\x1b[0m `,
'variable': `\x1b[38;5;123m`,
'red': `\x1b[38;5;197m`,
}
let logConsole
if ( config.verboseLogs === true ) {
logConsole = function ( message ) {
console.log( tags.info + message + tags.reset )
}
} else {
logConsole = function () {} // this is amazing and definitely not bad practice
}
console.log( tags.red + `RedlinePack ${ ver }\n` + tags.reset )
// funny regexes
const parenMatch = `\\s*\\(?\\s*(?:'|"|\\[\\[)+(.+?)(:?'|"|\\]\\])[\\s\\)]?` // yea, i know this is awful
const importDir = new RegExp( config.keywordDirectory + parenMatch, 'g' )
const importMulti = new RegExp( config.keywordMulti + parenMatch, 'g' )
const importSingle = new RegExp( config.keywordSingle + parenMatch, 'g' )
// indentation stuff
let singleTab = ' '.repeat( config.tabLength )
function indentString ( text, indentSize ) {
let tabs = singleTab.repeat( indentSize )
return text.split( /\n/ ).join( '\n' + tabs ) // theres prolly a better method than this but i couldnt find anything
}
// normally i'd inline this but i wont since there'll prob be tons of changes
function getIndentAmnt ( contents, importStatement ) {
let indentCount = 1
if ( config.smartIndents === true ) {
let location = contents.indexOf( importStatement ) // the position of the statement
// i'm sure theres a better method to find the line # a substring is in
// but i couldn't find any other reliable method
let prevText = contents.substring( 0, location ) // all the text before the statement
let lines = prevText.split( '\n' )
let thisLine = lines[lines.length - 1] // the line
let tabMatch = thisLine.match( /^([^\S\r\n])*/g )
if ( tabMatch ) {
let whitespace = tabMatch[0]
indentCount += whitespace.length / config.tabLength
}
}
return indentCount
}
// this is unnecessary but makes the packer source infinitely more easy to understand
class stringBuilder {
constructor() {
this.str = ''
};
indent( amount = 1 ) {
this.str += `\n${ singleTab.repeat( amount ) }`
return this
}
line( text = '' ) {
this.str += `${ text }\n`
return this
}
text( text ) {
this.str += text
return this
}
reset() {
this.str = ''
return this
}
result() {
return this.str
}
}
// the packer class is unnecessary but also makes things easier (atleast for me) so im leaving it in
class Packer {
constructor() {
this.imported = [] // keeps track of what file directories were already parsed
}
// Returns if this Packer has imported the file
isPathImported( file ) {
return ( config.redundantImporting ? false : this.imported.includes( file ) )
}
// Parses any import keywords found in a file, returns formatted contents
parseFile( filePath ) {
let fileExists = fs.existsSync( filePath )
let fileImported = this.isPathImported( filePath )
let fileIsFile = fileExists && fs.lstatSync( filePath ).isFile()
if ( !fileExists ) {
console.log( tags.error + `Failed to find the file "${ filePath }"` )
return {
'status': false,
'result': 1
}
}
if ( fileImported && !config.redundantImporting ) {
console.log( tags.warn + `File "${ filePath }" was already imported` )
return {
'status': false,
'result': 2
}
}
if ( !fileIsFile ) {
console.log( tags.error + `Attempted to import the directory "${ filePath }"` )
return {
'status': false,
'result': 3
}
}
this.imported.push( filePath )
let contents = fs.readFileSync( filePath ).toString()
let builder = new stringBuilder()
// Single imports (rewritten)
{
for ( const match of contents.matchAll( importSingle ) ) {
let importStatement = match[0] // the entire import statement ( ex. a('b/c.lua') )
let importPath = match[1] // the file path within the statement ( ex. b/c.lua )
let indentCount = getIndentAmnt( contents, importStatement )
let { status, result } = this.parseFile( importPath )
if ( !status ) {
builder.text( '(function() end)() -- ' )
switch ( result ) {
case 1:
builder.text( `Failed to find the file "${ importPath }"` )
break;
case 2:
builder.text( `File "${ importPath }" was already imported` )
break;
case 3:
builder.text( `Attempted to import a directory ("${ importPath }"), which is not a file!` )
break;
default:
builder.text( `An unknown error occured - "${ importPath }"` )
break;
}
contents = contents.replace( importStatement, builder.result() )
builder.reset()
continue
}
let importCnts = indentString( result, indentCount )
builder.text( '(function() ' )
if ( config.fileComments ) {
builder.text( `-- ${ importPath }` )
}
builder.indent( indentCount )
builder.text( importCnts )
builder.indent( indentCount - 1 ).text( 'end)()' )
let finalStr = builder.result().replaceAll( '$', '$$$$' ) // i love javascript!!
contents = contents.replace( importStatement, finalStr )
builder.reset()
}
};
// Multi imports (rewritten)
{
for ( const match of contents.matchAll( importMulti ) ) {
let importStatement = match[0] // the entire import statement ( ex. a('b/c.lua') )
let importPath = match[1] // the file path within the statement ( ex. b/c.lua )
if ( !importPath.endsWith( '/' ) ) {
importPath += '/'
}
if ( !fs.existsSync( importPath ) ) {
console.log( tags.error + `Failed to find the directory "${ importPath }"` )
builder.text( `(function() end)() -- ` + `Failed to find the directory "${ importPath }"` )
contents = contents.replace( importStatement, builder.result() )
builder.reset()
continue
}
if ( fs.lstatSync( importPath ).isFile() ) {
console.log( tags.error + `Attempted to import the file "${ importPath }"` )
builder.text( `(function() end)() -- ` + `Attempted to import a file ("${ importPath }"), which is not a directory!` )
contents = contents.replace( importStatement, builder.result() )
builder.reset()
continue
}
let indentCount = getIndentAmnt( contents, importStatement )
let dirFiles = fs.readdirSync( importPath )
if ( dirFiles.length > 0 ) {
for ( const file of dirFiles ) {
if ( path.extname(file) != '.lua' ) {
continue
}
let fullPath = importPath + file
let { status, result } = this.parseFile( fullPath )
if ( !status ) {
continue
}
let importCnts = indentString( result, indentCount )
builder.text( '(function() ' )
if ( config.fileComments ) {
builder.text( `-- ${ fullPath }` )
}
builder.indent( indentCount )
builder.text( importCnts )
builder.indent( indentCount - 1 ).text( 'end)(), ' )
}
let finalStr = builder.result().slice( 0, -2 ).replaceAll( '$', '$$$$' )
contents = contents.replace( importStatement, finalStr )
builder.reset()
} else {
console.log( tags.warn + `No files were found in the directory "${ importPath }"` )
builder.text( `(function() end)() -- ` + `No files were found in the directory "${ importPath }"` )
contents = contents.replace( importStatement, builder.result() )
builder.reset()
}
}
};
// Directory imports (rewritten)
{
for ( const match of contents.matchAll( importDir ) ) {
let importStatement = match[0] // the entire import statement ( ex. a('b/c.lua') )
let importPath = match[1] // the file path within the statement ( ex. b/c.lua )
if ( !importPath.endsWith( '/' ) ) {
importPath += '/'
}
if ( !fs.existsSync( importPath ) ) {
console.log( tags.error + `Failed to find the directory "${ importPath }"` )
builder.text( `(function() end)() -- ` + `Failed to find the directory "${ importPath }"` )
contents = contents.replace( importStatement, builder.result() )
builder.reset()
continue
}
if ( fs.lstatSync( importPath ).isFile() ) {
console.log( tags.error + `Attempted to import the file "${ importPath }"` )
builder.text( `(function() end)() -- ` + `Attempted to import a file ("${ importPath }"), which is not a directory!` )
contents = contents.replace( importStatement, builder.result() )
builder.reset()
continue
}
let indentCount = getIndentAmnt( contents, importStatement )
let dirFiles = fs.readdirSync( importPath )
if ( dirFiles.length > 0 ) {
builder.text( 'do ' )
if ( config.fileComments ) {
builder.text( `-- ${ importPath }` )
}
for ( const file of dirFiles ) {
if ( path.extname( file ) != '.lua' ) {
continue
}
let fullPath = importPath + file
if ( fullPath == config.inputFile ) {
console.log( tags.warn + 'Attempted to recursively import the input file!' + tags.reset )
continue
}
let { status, result } = this.parseFile( fullPath )
if ( !status ) {
continue
}
let importCnts = indentString( result, indentCount + 1 )
builder.indent( indentCount ).text( 'do ' )
if ( config.fileComments ) {
builder.text( `-- ${ fullPath }` )
}
builder.indent( indentCount + 1 )
builder.text( importCnts )
builder.indent( indentCount ).text( 'end' )
}
builder.indent( indentCount - 1 ).text( 'end' )
let finalStr = builder.result().replaceAll( '$', '$$$$' )
contents = contents.replace( importStatement, finalStr )
builder.reset()
} else {
console.log( tags.warn + `No files were found in the directory "${ importPath }"` )
builder.text( `(function() end)() -- ` + `No files were found in the directory "${ importPath }"` )
contents = contents.replace( importStatement, builder.result() )
builder.reset()
}
}
};
logConsole( 'Parsed file ' + filePath )
return {
'status': true,
'result': contents
}
};
};
if ( config.redundantImporting ) {
console.log( tags.warn + 'RedundantImporting is experimental, and may be unstable!' + tags.reset )
}
logConsole( 'Creating new Packer...' )
let thisPacker = new Packer()
let { status, result } = thisPacker.parseFile( config.inputFile )
logConsole( 'Finished packing!' )
if ( config.minify === true ) {
console.log( tags.info + 'Minifying output' + tags.reset )
result = luamin.minify( result )
}
if ( config.minify === true && config.packerWaterMark === true ) {
result = `-- Packed using RedlinePack ${ ver }\n\n` + result
} else if ( config.packerWatermark === true ) {
result = `-- Packed using RedlinePack ${ ver }\n` + result
}
fs.writeFileSync( config.outputFile, result )
console.log( tags.success + `Successfully packed ${ tags.variable + ( thisPacker.imported.length ) + tags.reset } file(s) into ${ tags.variable + config.outputFile + tags.reset }.` )