forked from shoelace-style/shoelace
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.js
345 lines (302 loc) · 8.66 KB
/
build.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
/* eslint prefer-arrow-callback: "warn" */
'use strict';
global.__version = require('./package.json').version;
require('dotenv').config();
const Promise = require('bluebird');
const AtImport = require('postcss-import');
const Chalk = require('chalk');
const CSSnano = require('cssnano');
const CSSnext = require('postcss-cssnext');
const Del = require('del');
const FS = Promise.promisifyAll(require('fs'));
const Layouts = require('metalsmith-layouts');
const Markdown = require('metalsmith-markdown');
const Metalsmith = require('metalsmith');
const Path = require('path');
const PostCSS = require('postcss');
const Program = require('commander');
const S3 = require('s3');
const UglifyJS = require('uglify-js');
const Watch = require('watch');
//
// Builds all doc pages.
//
// Returns a promise.
//
function buildDocs() {
return Promise.resolve()
.then(() => new Promise((resolve, reject) => {
Metalsmith(__dirname)
.source('./source/docs')
.destination('./docs')
.clean(true)
.use(Markdown())
.metadata({
version: __version
})
.use(Layouts({
engine: 'handlebars',
directory: './source/layouts',
rename: false
}))
// Update {{version}} in content since it's not processed with Handlebars
.use((files, metalsmith, done) => {
Object.keys(files).forEach((key) => {
let file = files[key];
file.contents = new Buffer(
file.contents
.toString()
.replace(/\{\{version\}\}/g, __version)
);
});
done();
})
.build((err) => {
if(err) {
reject(err);
return;
}
console.log(Chalk.green('Docs generated! 📚'));
resolve();
});
}));
}
//
// Builds all scripts.
//
// Returns a promise.
//
function buildScripts() {
return Promise.resolve()
// Create the dist folder if it doesn't exist
.then(() => {
if(!FS.existsSync(Path.join(__dirname, 'dist'))) {
return FS.mkdirAsync(Path.join(__dirname, 'dist'));
}
})
// Generate minified scripts
.then(() => new Promise((resolve, reject) => {
let scripts = {
'dropdowns.js': FS.readFileSync(Path.join(__dirname, 'source/js/dropdowns.js'), 'utf8'),
'tabs.js': FS.readFileSync(Path.join(__dirname, 'source/js/tabs.js'), 'utf8')
};
let result = UglifyJS.minify(scripts, {
output: {
comments: /^!/
}
});
if(result.error) {
reject(result.error);
return;
}
resolve(result.code);
}))
// Write minified scripts to dist
.then((scripts) => {
let file = Path.join(__dirname, 'dist/shoelace.js');
// Update {{version}} in JS since it's not processed with Handlebars
scripts = scripts.replace(/\{\{version\}\}/g, __version);
// Output a message
console.log(Chalk.green('JS processed: %s! 🐭'), Path.relative(__dirname, file));
// Write output file
return FS.writeFileAsync(file, scripts, 'utf8');
});
}
//
// Builds all stylesheets.
//
// Returns a promise.
//
function buildStyles() {
return Promise.resolve()
// Create the dist folder if it doesn't exist
.then(() => {
if(!FS.existsSync(Path.join(__dirname, 'dist'))) {
return FS.mkdirAsync(Path.join(__dirname, 'dist'));
}
})
// Generate minified stylesheet
.then(() => {
let file = Path.join(__dirname, 'source/css/shoelace.css');
let css = FS.readFileSync(file, 'utf8');
return PostCSS([
AtImport,
CSSnext({
features: {
rem: false
}
}),
CSSnano({
autoprefixer: false,
safe: true
})
]).process(css, { from: file });
})
// Write stylesheet to dist
.then((result) => {
let file = Path.join(__dirname, 'dist/shoelace.css');
// Update {{version}} in CSS since it's not processed with Handlebars
result.css = result.css.replace(/\{\{version\}\}/g, __version);
// Output a message
console.log(Chalk.green('CSS processed: %s! 🦋'), Path.relative(__dirname, file));
// Write output file
return FS.writeFileAsync(file, result.css, 'utf8');
});
}
//
// Publishes the dist folder to an S3 bucket.
//
//
//
function publishToS3() {
return new Promise((resolve, reject) => {
const client = S3.createClient({
s3Options: {
accessKeyId: process.env.S3_ACCESS_KEY,
secretAccessKey: process.env.S3_SECRET_KEY
}
});
// Sync the local /dist directory to /{version} in the S3 bucket
let uploader = client.uploadDir({
localDir: Path.join(__dirname, 'dist'),
deleteRemoved: true,
s3Params: {
ACL: process.env.S3_ACL,
Prefix: __version,
Bucket: process.env.S3_BUCKET
}
});
uploader.on('error', (err) => {
reject(err);
});
uploader.on('end', () => {
console.log(Chalk.green('%s has been published to S3! ☁️'), __version);
resolve();
});
});
}
//
// Watches a directory for changes
//
// - options (object)
// - path (string) - the path of the directory to watch.
// - ready (function) - callback to execute after initializing.
// - change (function(event, file)) - callback to execute when a file is changed.
//
// No return value.
//
function watch(options) {
options = options || {};
Watch.watchTree(options.path, {
ignoreDotFiles: true,
interval: 1
}, (file, current, previous) => {
if(typeof file === 'object' && previous === null && current === null) {
if(typeof options.ready === 'function') options.ready();
} else if(previous === null) {
if(typeof options.change === 'function') options.change({ type: 'created' }, file);
} else if(current.nlink === 0) {
if(typeof options.change === 'function') options.change({ type: 'deleted' }, file);
} else {
if(typeof options.change === 'function') options.change({ type: 'modified' }, file);
}
});
}
// Initialize CLI
Program
.version(__version)
.option('--build', 'Builds a release')
.option('--clean', 'Removes existing release')
.option('--s3', 'Publish lastest release to an S3 bucket (requires .env)')
.option('--watch', 'Watch for changes and build automatically')
.on('--help', () => {
console.log(Chalk.cyan('\n Version %s\n'), __version);
process.exit(1);
})
.parse(process.argv);
// Show help by default
if(!process.argv.slice(2).length) {
Program.outputHelp();
process.exit(1);
}
// Build
if(Program.build) {
Promise.resolve()
// Remove the dist folder
.then(() => Del(Path.join(__dirname, 'dist')))
// Build styles
.then(() => buildStyles())
// Minify scripts
.then(() => buildScripts())
// Generate docs
.then(() => buildDocs())
// Publish to S3 if --s3 flag is set
.then(() => Program.s3 ? publishToS3() : null)
// Exit with success
.then(() => process.exit(1))
// Handle errors
.catch((err) => {
console.error(Chalk.red(err));
process.exit(-1);
});
} else {
// Can't use the --s3 options without --build
if(Program.s3) {
console.error(Chalk.yellow('The --s3 flag can only be used with --build'));
process.exit(-1);
}
}
// Clean
if(Program.clean) {
Promise.resolve()
// Delete /dist
.then(() => Del(Path.join(__dirname, 'dist')))
.then(() => {
console.log(Chalk.green('/dist has been removed.'));
})
// Delete /docs
.then(() => Del(Path.join(__dirname, 'docs')))
.then(() => {
console.log(Chalk.green('/docs has been removed.'));
})
// Exit with success
.then(() => process.exit(1))
// Handle errors
.catch((err) => {
console.error(Chalk.red(err));
process.exit(-1);
});
}
// Watch
if(Program.watch) {
// Watch styles
watch({
path: Path.join(__dirname, 'source/css'),
ready: () => console.log(Chalk.cyan('Watching for style changes...')),
change: (event) => {
if(event.type === 'created' || event.type === 'modified') {
buildStyles();
}
}
});
// Watch scripts
watch({
path: Path.join(__dirname, 'source/js'),
ready: () => console.log(Chalk.cyan('Watching for scripts changes...')),
change: (event) => {
if(event.type === 'created' || event.type === 'modified') {
buildScripts();
}
}
});
// Watch docs
watch({
path: Path.join(__dirname, 'source/docs'),
ready: () => console.log(Chalk.cyan('Watching for docs changes...')),
change: (event) => {
if(event.type === 'created' || event.type === 'modified') {
buildDocs();
}
}
});
}