-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
91 lines (77 loc) · 2.7 KB
/
index.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
const fs = require('fs');
const path = require('path');
const util = require('util');
const p8tojs = {
async convertFile(inputFile, outputFile, options = {}) {
const input = await fs.promises.readFile(inputFile, 'utf8');
const output = `// ${path.basename(inputFile)}\n` + this.convert(input, options);
await fs.promises.writeFile(outputFile, output, 'utf8');
},
convertFileSync(inputFile, outputFile, options = {}) {
const input = fs.readFileSync(inputFile, 'utf8');
const output = `// ${path.basename(inputFile)}\n` + this.convert(input, options);
fs.writeFileSync(outputFile, output, 'utf8');
},
/**
* Converts an input PICO-8 cartridge string into a JS/JSON output.
*/
convert(input, options = {}) {
let sections = this._bySection(input);
if (options.sections && options.sections.length > 0) {
sections = options.sections.reduce((hash, key) => {
hash[key] = sections[key];
return hash;
}, {});
}
if (options.encoding === 'base64') {
for (let key of Object.keys(sections)) {
sections[key] = sections[key].split('\n').map(line => Buffer.from(line, 'hex').toString('base64')).join('\n');
}
}
let prefix = '';
let suffix = ';';
let formattedData = util.inspect(sections, {
colors: false,
maxStringLength: Infinity,
breakLength: Infinity,
sorted: true
});
switch (options.export) {
case 'commonjs':
prefix = 'module.exports = ';
break;
case 'default':
case undefined:
prefix = 'export default ';
break;
case 'json':
formattedData = JSON.stringify(sections, undefined, 2);
suffix = '';
break;
default:
prefix = `export const ${options.export} = `
break;
}
return prefix + formattedData + suffix;
},
_bySection(content) {
const lines = content.split(/\r?\n/);
const result = {};
let section;
for (let line of lines) {
line = line.trim();
let match = line.match(/^__(.+)__/);
if (match) {
section = match[1];
result[section] = [];
} else if (section) {
if (line.length > 0) result[section].push(line);
}
}
for (let key of Object.keys(result)) {
result[key] = result[key].join('\n');
}
return result;
}
};
module.exports = p8tojs;