This repository has been archived by the owner on Jul 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
124 lines (103 loc) · 2.64 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
const fs = require('fs');
const path = require('path');
function Copier (options) {
if (options == null) {
throw new ReferenceError('options muse be defined!');
}
if (options.items == null) {
throw new ReferenceError('items must be defined!');
}
if (!Array.isArray(options.items)) {
throw new TypeError('items must be an Array!');
}
var that = this;
/**
* Name of plugin
* @see {@link https://rollupjs.org/guide/en#name}
*/
this.name = 'rollup-plugin-copier';
/**
* Item to copy
* @typedef {Object} ToCopy
* @property {string} src - Source
* @property {string} dest - Destination
* @property {boolean=false} createPath - Create path if doesn't exist
*/
/**
* List of items to copy
* @type {ToCopy[]}
*/
this._items = options.items;
/**
* Verbose flag
* Set true if you want see what's going on currently. Default false
* @type boolean
*/
this._verbose = options.verbose == null ? false : options.verbose;
/**
* Hook on
* Default hook is 'buildOn', but you can change it with this property
* @type string
* @see {@link https://rollupjs.org/guide/en#buildEnd}
*/
this._hookOn = options.hookOn == null? 'buildEnd' : options.hookOn;
/**
* Hook
*/
this[this._hookOn] = function() {
var promises = that._items.map(function(item) {
item.createPath = item.createPath == null ? false : item.createPath;
return new Promise(function(resolve, reject) {
that._debug(`${item.src} → ${item.dest}`);
if (!that._itemDestinationExists(item)) {
reject(`Destination for file ${item.dest} doesn't exist`);
return;
}
fs.copyFile(item.src, item.dest, function(err) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
});
return Promise.all(promises);
};
/**
* Debug
* @param msg {string}
* @private
*/
this._debug = function(msg) {
if (that._verbose) {
console.log(`rollup-plugin-copier: ${msg}`); // eslint-disable-line no-console
}
};
/**
* Item destination exists
* @param item {ToCopy}
* @private
*/
this._itemDestinationExists = function(item) {
if (fs.existsSync(path.dirname(item.dest))) {
return true;
} else if (item.createPath) {
mkDirP(item.dest);
return true;
} else {
return false;
}
};
}
function mkDirP(dest) {
var dirName = path.dirname(dest);
if (!fs.existsSync(dirName)) {
mkDirP(dirName);
fs.mkdirSync(dirName);
}
}
function plugin (options) {
return new Copier(options);
}
module.exports = plugin;