www

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | Submodules | README | LICENSE

utils.js (3087B)


      1 const path = require('path');
      2 const fs = require('fs-extra');
      3 const colors = require('colors/safe');
      4 const green = colors.green;
      5 const blue = colors.blue;
      6 const yellow = colors.yellow;
      7 const isWindows = /^win/.test(process.platform);
      8 
      9 const ROOT = path.resolve(__dirname, '..');
     10 const NODE_ENV = process.env.NODE_ENV;
     11 
     12 
     13 function onError(err) {
     14 	console.log(colors.red('Error:'), err);
     15 }
     16 
     17 function onSuccess(result) {
     18 	var msg = `${green('Success:')} ${blue(`[${result.action}]`)} ${result.count} files processed`;
     19 	if (result.totalCount) {
     20 		msg += ` (out of total ${result.totalCount} matched)`; 
     21 	}
     22 
     23 	msg += ` [${yellow(`${result.processingTime}ms`)}]`;	
     24 
     25 	console.log(msg);
     26 }
     27 
     28 function onProgress(sourcefile, outfile, operation) {
     29 	if ('isError' in global && global.isError) {
     30 		return;
     31 	}
     32 	if (NODE_ENV == 'debug') {
     33 		console.log(`${colors.blue(`[${operation}]`)} ${sourcefile} -> ${outfile}`);
     34 	} else {
     35 		console.log(`${colors.blue(`[${operation}]`)} ${sourcefile}`);
     36 	}
     37 }
     38 
     39 async function getSignatures() {
     40 	let signaturesFile = path.resolve(ROOT, '.signatures.json');
     41 	var signatures = {};
     42 	try {
     43 		signatures = await fs.readJson(signaturesFile);
     44 	} catch (_) {
     45 		// if signatures files doesn't exist, return empty object istead
     46 	}
     47 	return signatures;
     48 }
     49 
     50 async function writeSignatures(signatures) {
     51 	let signaturesFile = path.resolve(ROOT, '.signatures.json');
     52 	NODE_ENV == 'debug' && console.log('writing signatures to .signatures.json');
     53 	await fs.outputJson(signaturesFile, signatures);
     54 }
     55 
     56 async function cleanUp(signatures) {
     57 	const t1 = Date.now();
     58 	var removedCount = 0, invalidCount = 0;
     59 
     60 	for (let f of Object.keys(signatures)) {
     61 		try {
     62 			// check if file from signatures exists in source
     63 			await fs.access(f, fs.constants.F_OK);
     64 		} catch (_) {
     65 			invalidCount++;
     66 			NODE_ENV == 'debug' && console.log(`File ${f} found in signatures but not in src, deleting from build`);
     67 			try {
     68 				await fs.remove(path.join('build', f));
     69 				removedCount++;
     70 			} catch (_) {
     71 				// file wasn't in the build either
     72 			}
     73 			delete signatures[f];
     74 		}
     75 	}
     76 
     77 	const t2 = Date.now();
     78 	return {
     79 		action: 'cleanup',
     80 		count: removedCount,
     81 		totalCount: invalidCount,
     82 		processingTime: t2 - t1
     83 	};
     84 }
     85 
     86 async function getFileSignature(file) {
     87 	let stats = await fs.stat(file);
     88 	return {
     89 		mode: stats.mode,
     90 		mtime: stats.mtimeMs || stats.mtime.getTime(),
     91 		isDirectory: stats.isDirectory(),
     92 		isFile: stats.isFile()
     93 	};
     94 }
     95 
     96 function compareSignatures(a, b) {
     97 	return typeof a === 'object'
     98 	&& typeof b === 'object' 
     99 	&& a != null
    100 	&& b != null
    101 	&& ['mode', 'mtime', 'isDirectory', 'isFile'].reduce((acc, k) => {
    102 		return acc ? k in a && k in b && a[k] == b[k] : false;
    103 	}, true);
    104 }
    105 
    106 function getPathRelativeTo(f, dirName) {
    107 	return path.relative(path.join(ROOT, dirName), path.join(ROOT, f));
    108 }
    109 
    110 const formatDirsForMatcher = dirs => {
    111 	return dirs.length > 1 ? `{${dirs.join(',')}}` : dirs[0];
    112 };
    113 
    114 module.exports = {
    115 	isWindows,
    116 	onError,
    117 	onProgress,
    118 	onSuccess,
    119 	cleanUp,
    120 	getSignatures,
    121 	getFileSignature,
    122 	compareSignatures,
    123 	writeSignatures,
    124 	getPathRelativeTo,
    125 	formatDirsForMatcher
    126 };