forked from foundryvtt-starfinder/foundryvtt-starfinder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.js
571 lines (475 loc) · 14.6 KB
/
gulpfile.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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
const { AsyncNedb } = require('nedb-async');
const archiver = require('archiver');
const argv = require('yargs').argv;
const chalk = require('chalk');
const fs = require('fs-extra');
const gulp = require('gulp');
const less = require('gulp-less');
const path = require('path');
const sanitize = require("sanitize-filename");
const stringify = require('json-stringify-pretty-compact');
const SFRPG_LESS = ["src/less/*.less"];
function getConfig() {
const configPath = path.resolve(process.cwd(), 'foundryconfig.json');
let config;
if (fs.existsSync(configPath)) {
config = fs.readJSONSync(configPath);
return config;
} else {
return;
}
}
function getManifest() {
const json = {};
if (fs.existsSync('src')) {
json.root = 'src';
} else {
json.root = 'dist';
}
const modulePath = path.join(json.root, 'module.json');
const systemPath = path.join(json.root, 'system.json');
if (fs.existsSync(modulePath)) {
json.file = fs.readJSONSync(modulePath);
json.name = 'module.json';
} else if (fs.existsSync(systemPath)) {
json.file = fs.readJSONSync(systemPath);
json.name = 'system.json';
} else {
return;
}
return json;
}
/********************/
/* BUILD */
/********************/
/**
* Build Less
*/
function buildLess() {
const name = 'sfrpg';
return gulp
.src(`src/less/${name}.less`)
.pipe(less())
.pipe(gulp.dest('dist'));
}
/**
* Copy static files
*/
async function copyFiles() {
const name = 'sfrpg';
const statics = [
'lang',
'fonts',
'images',
'templates',
'icons',
'packs',
'module',
`${name}.js`,
'module.json',
'system.json',
'template.json',
];
try {
for (const file of statics) {
if (fs.existsSync(path.join('src', file))) {
await fs.copy(path.join('src', file), path.join('dist', file));
}
}
return Promise.resolve();
} catch (err) {
Promise.reject(err);
}
}
/**
* Does the same as copyFiles, except it only moves the
* README, OGL, and LICENSE files. These aren't needed for
* development, but they should be in the package.
*/
async function copyReadmeAndLicenses() {
const statics = ["README.md", "OGL", "LICENSE"];
try {
for (const file of statics) {
if (fs.existsSync(file)) {
await fs.copy(file, path.join('dist', file));
}
}
return Promise.resolve();
} catch (err) {
Promise.reject(err);
}
}
async function copyLibs() {
const tippyLib = "tippy.js/dist/tippy.umd.min.js";
const tippyMap = "tippy.js/dist/tippy.umd.min.js.map";
const popperLib = "@popperjs/core/dist/umd";
const cssFile = "tippy.js/dist/tippy.css";
const nodeModulesPath = "node_modules";
try {
await fs.copy(path.join(nodeModulesPath, tippyLib), "dist/lib/tippy/tippy.min.js");
await fs.copy(path.join(nodeModulesPath, tippyMap), "dist/lib/tippy/tippy.umd.min.js.map");
await fs.copy(path.join(nodeModulesPath, popperLib), "dist/lib/popperjs/core");
await fs.copy(path.join(nodeModulesPath, cssFile), "dist/styles/tippy.css");
return Promise.resolve();
} catch (err) {
Promise.reject(err);
}
}
/**
* Watch for changes for each build step
*/
function buildWatch() {
gulp.watch('src/**/*.less', { ignoreInitial: false }, buildLess);
gulp.watch(
['src/fonts', 'src/templates', 'src/lang', 'src/*.json', 'src/**/*.js'],
{ ignoreInitial: false },
copyFiles
);
}
/**
* Unpack existing db files into json files.
*/
async function unpack(sourceDatabase, outputDirectory) {
await fs.mkdir(`${outputDirectory}`, { recursive: true }, (err) => { if (err) throw err; });
let db = new AsyncNedb({ filename: sourceDatabase, autoload: true });
let items = await db.asyncFind({});
for (let item of items) {
let jsonOutput = JSON.stringify(item, null, 2);
let filename = sanitize(item.name);
filename = filename.replace(/[\s]/g,"_");
filename = filename.replace(/[,;]/g,"");
filename = filename.toLowerCase();
let targetFile = `${outputDirectory}/${filename}.json`;
await fs.writeFileSync(targetFile, jsonOutput, {"flag": "w"});
}
}
async function unpackPacks() {
console.log(`Unpacking all packs`);
let sourceDir = "./src/packs";
let files = await fs.readdirSync(sourceDir);
for (let file of files) {
if (file.endsWith(".db")) {
let fileWithoutExt = file.substr(0, file.length - 3);
let unpackDir = `./src/items/${fileWithoutExt}`;
let sourceFile = `${sourceDir}/${file}`;
console.log(`Processing ${fileWithoutExt}`);
console.log(`> Cleaning up ${unpackDir}`);
await fs.rmdirSync(unpackDir, {recursive: true});
console.log(`> Unpacking ${sourceFile} into ${unpackDir}`);
await unpack(sourceFile, unpackDir);
console.log(`> Done.`);
}
}
console.log(`\nUnpack finished.\n`);
return 0;
}
/**
* Cook db source json files into .db files with nedb
*/
var cookErrorCount = 0;
async function cookPacks() {
console.log(`Cooking db files`);
let compendiumMap = {};
let allItems = [];
let sourceDir = "./src/items";
let directories = await fs.readdirSync(sourceDir);
for (let directory of directories) {
let itemSourceDir = `${sourceDir}/${directory}`;
let outputFile = `./src/packs/${directory}.db`;
console.log(`Processing ${directory}`);
if (fs.existsSync(outputFile)) {
console.log(`> Removing ${outputFile}`);
await fs.unlinkSync(outputFile);
}
compendiumMap[directory] = {};
let db = new AsyncNedb({ filename: outputFile, autoload: true });
console.log(`Opening files in ${itemSourceDir}`);
let files = await fs.readdirSync(itemSourceDir);
for (let file of files) {
let filePath = `${itemSourceDir}/${file}`;
let jsonInput = await fs.readFileSync(filePath);
jsonInput = JSON.parse(jsonInput);
compendiumMap[directory][jsonInput._id] = jsonInput;
allItems.push({pack: directory, data: jsonInput});
await db.asyncInsert(jsonInput);
}
}
console.log(`\nStarting consistency check.`);
for (let item of allItems) {
let data = item.data;
if (!data || !data.data || !data.data.description) continue;
let desc = data.data.description.value;
if (!desc) continue;
let pack = item.pack;
let errors = [];
let itemMatch = [...desc.matchAll(/@Item\[([^\]]*)\]{([^}]*)}/gm)];
if (itemMatch && itemMatch.length > 0) {
for (let localItem of itemMatch) {
let localItemId = localItem[1];
let localItemName = localItem[2];
if (!(pack in compendiumMap)) {
errors.push(`Referencing non-existing compendium! '${localItemName} (${localItemId})' cannot find pack '${pack}'.`);
} else if (!(localItemId in compendiumMap[pack])) {
errors.push(`Referencing non-existing item id! '${localItemName} (${localItemId})' not found in pack '${pack}'.`);
}
}
}
let compendiumMatch = [...desc.matchAll(/@Compendium\[sfrpg\.([^\.]*)\.([^\]]*)\]{([^}]*)}/gm)];
if (compendiumMatch && compendiumMatch.length > 0) {
for (let otherItem of compendiumMatch) {
let otherPack = otherItem[1];
let otherItemId = otherItem[2];
let otherItemName = otherItem[3];
if (!(otherPack in compendiumMap)) {
errors.push(`Referencing non-existing compendium! '${otherItemName} (${otherItemId})' cannot find '${pack}'`);
} else if (!(otherItemId in compendiumMap[otherPack])) {
errors.push(`Referencing non-existing item id! '${otherItemName} (${otherItemId})' not found in pack '${otherPack}'.`);
}
}
}
if (errors.length > 0) {
console.log(`\n> ${data.name} errors:`);
for (let error of errors) {
console.log(error);
cookErrorCount++;
}
}
}
console.log(`\nUpdating items with updated IDs.\n`);
await unpackPacks();
console.log(`\nCook finished with ${cookErrorCount} errors.\n`);
return 0;
}
async function postCook() {
console.log(`\nCompendiums cooked with ${cookErrorCount} errors!\nDon't forget to restart Foundry to refresh compendium data!\n`);
return 0;
}
/********************/
/* CLEAN */
/********************/
/**
* Remove built files from `dist` folder
* while ignoring source files
*/
async function clean() {
const name = 'sfrpg';
const files = [];
files.push(
'lang',
'templates',
'module',
'fonts',
'icons',
'images',
'packs',
'lib',
'styles',
`${name}.js`,
`${name}.css`,
'module.json',
'system.json',
'template.json',
'README.md',
'OGL',
'LICENSE'
);
console.log(' ', chalk.yellow('Files to clean:'));
console.log(' ', chalk.blueBright(files.join('\n ')));
// Attempt to remove the files
try {
for (const filePath of files) {
await fs.remove(path.join('dist', filePath));
}
return Promise.resolve();
} catch (err) {
Promise.reject(err);
}
}
/********************/
/* LINK */
/********************/
/**
* Link build to User Data folder
*/
async function linkUserData() {
const name = 'sfrpg';
const config = fs.readJSONSync('foundryconfig.json');
let destDir;
try {
if (
fs.existsSync(path.resolve('.', 'dist', 'module.json')) ||
fs.existsSync(path.resolve('.', 'src', 'module.json'))
) {
destDir = 'modules';
} else if (
fs.existsSync(path.resolve('.', 'dist', 'system.json')) ||
fs.existsSync(path.resolve('.', 'src', 'system.json'))
) {
destDir = 'systems';
} else {
throw Error(
`Could not find ${chalk.blueBright(
'module.json'
)} or ${chalk.blueBright('system.json')}`
);
}
let linkDir;
if (config.dataPath) {
if (!fs.existsSync(path.join(config.dataPath, 'Data')))
throw Error('User Data path invalid, no Data directory found');
linkDir = path.join(config.dataPath, 'Data', destDir, name);
} else {
throw Error('No User Data path defined in foundryconfig.json');
}
if (argv.clean || argv.c) {
console.log(
chalk.yellow(`Removing build in ${chalk.blueBright(linkDir)}`)
);
await fs.remove(linkDir);
} else if (!fs.existsSync(linkDir)) {
console.log(
chalk.green(`Copying build to ${chalk.blueBright(linkDir)}`)
);
await fs.symlink(path.resolve('./dist'), linkDir);
}
return Promise.resolve();
} catch (err) {
Promise.reject(err);
}
}
/*********************/
/* PACKAGE */
/*********************/
/**
* Package build
*/
async function packageBuild() {
const manifest = getManifest();
try {
// Remove the package dir without doing anything else
if (argv.clean || argv.c) {
console.log(chalk.yellow('Removing all packaged files'));
await fs.remove('package');
return;
}
// Ensure there is a directory to hold all the packaged versions
await fs.ensureDir('package');
// Initialize the zip file
const zipName = `${manifest.file.name}-v${manifest.file.version}.zip`;
const zipFile = fs.createWriteStream(path.join('package', zipName));
const zip = archiver('zip', { zlib: { level: 9 } });
zipFile.on('close', () => {
console.log(chalk.green(zip.pointer() + ' total bytes'));
console.log(chalk.green(`Zip file ${zipName} has been written`));
return Promise.resolve();
});
zip.on('error', err => {
throw err;
});
zip.pipe(zipFile);
// Add the directory with the final code
zip.directory('dist/', manifest.file.name);
zip.finalize();
} catch (err) {
Promise.reject(err);
}
}
/*********************/
/* PACKAGE */
/*********************/
/**
* Update version and URLs in the manifest JSON
*/
function updateManifest(cb) {
const packageJson = fs.readJSONSync('package.json');
const config = getConfig(),
manifest = getManifest(),
rawURL = config.rawURL,
repoURL = config.repository,
manifestRoot = manifest.root;
if (!config) cb(Error(chalk.red('foundryconfig.json not found')));
if (!manifest) cb(Error(chalk.red('Manifest JSON not found')));
if (!rawURL || !repoURL)
cb(
Error(
chalk.red(
'Repository URLs not configured in foundryconfig.json'
)
)
);
try {
const version = argv.update || argv.u;
/* Update version */
const versionMatch = /^(\d{1,}).(\d{1,}).(\d{1,})$/;
const currentVersion = manifest.file.version;
let targetVersion = '';
if (!version) {
cb(Error('Missing version number'));
}
if (versionMatch.test(version)) {
targetVersion = version;
} else {
targetVersion = currentVersion.replace(
versionMatch,
(substring, major, minor, patch) => {
if (version === 'major') {
return `${Number(major) + 1}.0.0`;
} else if (version === 'minor') {
return `${major}.${Number(minor) + 1}.0`;
} else if (version === 'patch') {
return `${major}.${minor}.${Number(minor) + 1}`;
} else {
return '';
}
}
);
}
if (targetVersion === '') {
return cb(Error(chalk.red('Error: Incorrect version arguments.')));
}
if (targetVersion === currentVersion) {
return cb(
Error(
chalk.red(
'Error: Target version is identical to current version.'
)
)
);
}
console.log(`Updating version number to '${targetVersion}'`);
packageJson.version = targetVersion;
manifest.file.version = targetVersion;
/* Update URLs */
const result = `${rawURL}/v${manifest.file.version}/package/${manifest.file.name}-v${manifest.file.version}.zip`;
manifest.file.url = repoURL;
manifest.file.manifest = `${rawURL}/master/${manifestRoot}/${manifest.name}`;
manifest.file.download = result;
const prettyProjectJson = stringify(manifest.file, { maxLength: 35 });
fs.writeJSONSync('package.json', packageJson, { spaces: 2 });
fs.writeFileSync(
path.join(manifest.root, manifest.name),
prettyProjectJson,
'utf8'
);
return cb();
} catch (err) {
cb(err);
}
}
const execBuild = gulp.parallel(buildLess, copyFiles, copyLibs);
exports.build = gulp.series(clean, execBuild);
exports.watch = buildWatch;
exports.clean = clean;
exports.link = linkUserData;
exports.libs = copyLibs;
exports.package = gulp.series(copyReadmeAndLicenses, packageBuild);
exports.publish = gulp.series(
clean,
updateManifest,
execBuild,
copyReadmeAndLicenses,
packageBuild
);
exports.cook = gulp.series(cookPacks, clean, execBuild, postCook);
exports.unpack = unpackPacks;
exports.default = gulp.series(clean, execBuild);