UNPKG

2.69 kBJavaScriptView Raw
1///@ts-check
2"use strict";
3
4const through = require('through2');
5const chalk = require('ansi-colors');
6const PluginError = require('../lib/error');
7const prettyBytes = require('../lib/pretty-bytes');
8const prettyTime = require('../lib/pretty-time');
9
10const StreamCounter = require('../lib/byte-counter');
11const titleColor = require('./color');
12const fancyLog = require('./logger');
13
14
15
16module.exports = opts => {
17 opts = Object.assign({
18 pretty: true,
19 showTotal: true
20 }, opts);
21
22 let totalSize = 0;
23 let fileCount = 0;
24 const time = process.hrtime();
25
26 function log(sym, what, size, duration, highlightSize) {
27 let title = opts.title;
28 title = title ? titleColor(title) : '';
29 if (opts.sub) {
30 sym += chalk.cyanBright(`<${chalk.bold.underline(opts.sub)}>`);
31 }
32 size = opts.pretty ? prettyBytes(size) : (size + ' B');
33 duration = duration ? chalk.gray("[" + prettyTime(duration) + "]") : '';
34 fancyLog(title, sym, what, chalk.gray('(') + chalk[highlightSize ? 'magentaBright' : 'gray'](size) + chalk.gray(')') + duration);
35 }
36
37 return through.obj((file, enc, cb) => {
38 if (file.isNull()) {
39 cb(null, file);
40 return;
41 }
42
43 const finish = (err, size) => {
44 if (err) {
45 cb(new PluginError('size', err));
46 return;
47 }
48
49 totalSize += size;
50
51 if (opts.showFiles === true && size > 0) {
52 log(
53 chalk.reset.whiteBright('[√]'),
54 chalk.green.underline.bold(opts.showTotal ? chalk.dim(file.relative) : file.relative),
55 size,
56 !opts.showTotal);
57 }
58
59 fileCount++;
60 cb(null, file);
61 };
62
63 if (file.isStream()) {
64
65 file.contents.pipe(new StreamCounter())
66 .on('error', finish)
67 .on('finish', function () {
68 finish(null, this.bytes);
69 });
70 return;
71 }
72
73
74 finish(null, file.contents.length);
75
76 }, function (cb) {
77 // @ts-ignore
78 this.size = totalSize;
79 // @ts-ignore
80 this.prettySize = prettyBytes(totalSize);
81
82 if (!(fileCount === 1 && opts.showFiles) && totalSize > 0 && fileCount > 0 && opts.showTotal) {
83 const diff = process.hrtime(time);
84 const duration = diff[0] * 1e9 + diff[1]
85 log(chalk.reset.bold.greenBright.italic('√'), chalk.green('All ' + fileCount + (fileCount > 1 ? ' files' : ' file') + ' done!'), totalSize, duration, true);
86 }
87 cb();
88 });
89};
\No newline at end of file