/
index.js
151 lines (128 loc) · 5.23 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
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
'use strict';
const fs = require('fs');
const COS = require('cos-nodejs-sdk-v5');
const path = require('path');
const ora = require('ora');
const isRegExp = require('lodash.isregexp');
// Constants
const REGEXP_HASH = /\[hash(?::(\d+))?\]/gi;
// Uploading progress tip
const tip = (uploaded, total) => {
let percentage = total == 0 ? 0 : Math.round((uploaded / total) * 100);
return `Uploading to Tencent COS: ${percentage == 0 ? '' : percentage + '% '}${uploaded}/${total} files uploaded`;
};
// Replace path variable by hash with length
const withHashLength = replacer => {
return function(_, hashLength) {
const length = hashLength && parseInt(hashLength, 10);
const hash = replacer.apply(this, arguments);
return length ? hash.slice(0, length) : hash;
};
};
// Perform hash replacement
const getReplacer = (value, allowEmpty) => {
return function(match) {
// last argument in replacer is the entire input string
const input = arguments[arguments.length - 1];
if (value === null || value === undefined) {
if (!allowEmpty) throw new Error(`Path variable ${match} not implemented in this context of qn-webpack plugin: ${input}`);
return '';
} else {
return `${value}`;
}
};
};
module.exports = class CosPlugin {
constructor(options) {
this.options = Object.assign({}, options);
}
apply(compiler) {
compiler.plugin('after-emit', (compilation, callback) => {
let basePath = path.basename(compiler.outputPath);
let assets = compilation.assets;
let hash = compilation.hash;
let uploadPath = this.options.path || '[hash]';
let exclude = isRegExp(this.options.exclude) && this.options.exclude;
let include = isRegExp(this.options.include) && this.options.include;
let batch = this.options.batch || 20;
let cos = new COS({
SecretId: this.options.secretId,
SecretKey: this.options.secretKey,
FileParallelLimit: batch,
ChunkParallelLimit: batch
});
let bucket = this.options.bucket;
let region = this.options.region;
uploadPath = uploadPath.replace(REGEXP_HASH, withHashLength(getReplacer(hash)));
let filesNames = Object.keys(assets);
let totalFiles = 0;
let uploadedFiles = 0;
// Mark finished
let _finish = err => {
spinner.succeed();
// eslint-disable-next-line no-console
console.log('\n');
callback(err);
};
// Filter files that should be uploaded
filesNames = filesNames.filter(fileName => {
let file = assets[fileName] || {};
// Ignore unemitted files
if (!file.emitted) return false;
// Check excluced files
if (exclude && exclude.test(file.existsAt)) return false;
// Check included files
if (include) return include.test(file.existsAt);
return true;
});
totalFiles = filesNames.length;
// eslint-disable-next-line no-console
console.log('\n');
let spinner = ora({
text: tip(0, totalFiles),
color: 'green'
}).start();
// Perform upload to cos
const performUpload = function(fileName) {
let file = assets[fileName] || {};
fileName = basePath + '/' + fileName.replace(/\\/g, '/');
let key = path.posix.join(uploadPath, fileName);
return new Promise((resolve, reject) => {
let begin = Date.now();
cos.putObject(
{
Bucket: bucket,
Region: region,
Key: key,
Body: fs.createReadStream(file.existsAt),
ContentLength: fs.statSync(file.existsAt).size
},
function(err, body) {
uploadedFiles++;
spinner.text = tip(uploadedFiles, totalFiles);
if (err) return reject(err);
body.duration = Date.now() - begin;
resolve(body);
}
);
});
};
// Execute stack according to `batch` option
const execStack = function(err) {
if (err) {
// eslint-disable-next-line no-console
console.log('\n');
return Promise.reject(err);
}
// Get 20 files
let _files = filesNames.splice(0, batch);
if (_files.length) {
return Promise.all(_files.map(performUpload)).then(() => execStack(), execStack);
} else {
return Promise.resolve();
}
};
execStack().then(() => _finish(), _finish);
});
}
};