1 | #!/usr/bin/env node
|
2 |
|
3 | var path = require('path'),
|
4 | fs = require('fs');
|
5 |
|
6 | var async = require('async'),
|
7 | request = require('request'),
|
8 | mkdirp = require('mkdirp'),
|
9 | cjson = require('cjson'),
|
10 | _ = require('lodash'),
|
11 | fastGlob = require('fast-glob'),
|
12 | isGlob = require('is-glob'),
|
13 | UglifyJS = require('uglify-js'),
|
14 | md5 = require('md5'),
|
15 | isUtf8 = require('is-utf8');
|
16 |
|
17 | var logger = require('note-down');
|
18 | logger.removeOption('showLogLine');
|
19 |
|
20 | var chalk = logger.chalk;
|
21 |
|
22 | var argv = require('yargs')
|
23 | .help(false)
|
24 | .version(false)
|
25 | .argv;
|
26 |
|
27 | var packageJson = require('./package.json');
|
28 |
|
29 | var nodeVersion = process.versions.node;
|
30 | var paramHelp = argv.h || argv.help,
|
31 | paramVersion = argv.v || argv.version,
|
32 | paramVerbose = argv.verbose,
|
33 | paramOutdated = argv.outdated,
|
34 | paramWhenFileExists = argv.whenFileExists;
|
35 |
|
36 | var cwd = process.cwd();
|
37 |
|
38 | var utils = {
|
39 |
|
40 |
|
41 |
|
42 | stripBom: function (string) {
|
43 | if (string.charCodeAt(0) === 0xFEFF) {
|
44 | return string.slice(1);
|
45 | }
|
46 | return string;
|
47 | },
|
48 |
|
49 | getEncoding: function(contents) {
|
50 | return isUtf8(contents) ? 'utf8' : 'binary';
|
51 | },
|
52 | getColoredTypeString: function(encoding) {
|
53 | switch (encoding) {
|
54 | case 'remote': return chalk.cyan('remote');
|
55 | case 'binary': return chalk.yellow('binary');
|
56 | case 'utf8': return ' utf8 ';
|
57 | default: return chalk.red(encoding);
|
58 | }
|
59 | },
|
60 | isRemoteResource: function (resourcePath) {
|
61 | if (
|
62 | resourcePath.indexOf('https://') === 0 ||
|
63 | resourcePath.indexOf('http://') === 0 ||
|
64 | resourcePath.indexOf('ftp://') === 0
|
65 | ) {
|
66 | return true;
|
67 | }
|
68 | return false;
|
69 | },
|
70 | getRelativePath: function (wrt, fullPath) {
|
71 | if (utils.isRemoteResource(fullPath)) {
|
72 | return fullPath;
|
73 | }
|
74 | return path.relative(wrt, fullPath);
|
75 | },
|
76 |
|
77 | exitWithError: function (e, errMsg) {
|
78 | if (errMsg) {
|
79 | logger.log(chalk.magenta(errMsg));
|
80 | }
|
81 | if (e) {
|
82 | logger.error(e);
|
83 | }
|
84 | process.exit(1);
|
85 | },
|
86 |
|
87 |
|
88 | booleanIntention: function (val, defaultValue) {
|
89 | if (val === undefined) {
|
90 | return defaultValue;
|
91 | } else {
|
92 | return !!val;
|
93 | }
|
94 | },
|
95 |
|
96 | ensureDirectoryExistence: function(dirPath) {
|
97 | var dirname = dirPath[dirPath.length-1] === '/' ? path.normalize(dirPath) : path.dirname(dirPath);
|
98 | if (!fs.existsSync(dirPath)) {
|
99 | try {
|
100 | mkdirp.sync(dirname);
|
101 | } catch (e) {
|
102 | logger.error('\n' + chalk.bold.underline('Error:'));
|
103 | logger.error('Unable to create directory ' + dirname);
|
104 |
|
105 | logger.error('\n' + chalk.bold.underline('Error details:'));
|
106 | logger.error(e);
|
107 |
|
108 | process.exit(1);
|
109 | }
|
110 | }
|
111 | },
|
112 |
|
113 | doUglify: function (needsUglify, code, cb) {
|
114 | if (needsUglify) {
|
115 | var result = UglifyJS.minify(
|
116 | code,
|
117 |
|
118 | {
|
119 | compress: {
|
120 | sequences: false
|
121 | },
|
122 | mangle: false,
|
123 | output: {
|
124 | semicolons: false,
|
125 | comments: 'some'
|
126 | }
|
127 | }
|
128 | );
|
129 | var consoleCommand = 'uglifyjs <source> --compress sequences=false --beautify beautify=false,semicolons=false,comments=some --output <destination>';
|
130 | cb(result.code, consoleCommand);
|
131 | } else {
|
132 | cb(code, null);
|
133 | }
|
134 | },
|
135 |
|
136 | readContents: function (sourceFullPath, cb) {
|
137 | if (utils.isRemoteResource(sourceFullPath)) {
|
138 | request(
|
139 | {
|
140 | uri: sourceFullPath,
|
141 | gzip: true,
|
142 | timeout: 30000
|
143 | },
|
144 | function (err, response, body) {
|
145 | if (err) {
|
146 | cb(err);
|
147 | } else {
|
148 | if (response.statusCode === 200) {
|
149 | cb(null, body, 'remote');
|
150 | } else {
|
151 | cb('Unexpected statusCode (' + response.statusCode + ') for response of: ' + sourceFullPath);
|
152 | }
|
153 | }
|
154 | }
|
155 | );
|
156 | } else {
|
157 | try {
|
158 | var rawContents = fs.readFileSync(sourceFullPath);
|
159 | var encoding = utils.getEncoding(rawContents);
|
160 | var contents = encoding === 'binary'
|
161 | ? rawContents
|
162 | : rawContents.toString('utf8');
|
163 | cb(null, contents, encoding);
|
164 | } catch (e) {
|
165 | cb(e);
|
166 | }
|
167 | }
|
168 | }
|
169 | };
|
170 |
|
171 | if (module.parent) {
|
172 |
|
173 | logger.warn('\nWarning: Please run this module (' + packageJson.name + ') from its binary file.' + '\n');
|
174 | } else {
|
175 | var showHelp = function () {
|
176 | logger.log([
|
177 | '',
|
178 | chalk.bold('Usage:'),
|
179 | ' copy-files-from-to [--config <config-file>] [--mode <mode-name>] [...]',
|
180 | '',
|
181 | chalk.bold('Examples:'),
|
182 | ' copy-files-from-to',
|
183 | ' copy-files-from-to --config copy-files-from-to.json',
|
184 | ' copy-files-from-to --mode production',
|
185 | ' copy-files-from-to -h',
|
186 | ' copy-files-from-to --version',
|
187 | '',
|
188 | chalk.bold('Options:'),
|
189 | ' --config <config-file-path> Path to configuration file',
|
190 | ' When unspecified, it looks for copy-files-from-to.cjson / copy-files-from-to.json',
|
191 | ' --mode <mode-name> Mode to use for copying the files',
|
192 | ' When unspecified, it uses "default" mode',
|
193 | ' --when-file-exists <operation> Override "whenFileExists" setting specified in configuration file',
|
194 | ' <operation> can be "notify-about-available-change" or "overwrite" or "do-nothing"',
|
195 | ' --outdated Notify about outdated parts of the configuration file',
|
196 | ' (takes cue from "latest" property, wherever specified)',
|
197 | ' --verbose Verbose logging',
|
198 | ' -v --version Output the version number',
|
199 | ' -h --help Show help',
|
200 | ''
|
201 | ].join('\n'));
|
202 | };
|
203 |
|
204 | if (paramHelp) {
|
205 | showHelp();
|
206 | process.exit(0);
|
207 | }
|
208 |
|
209 | if (paramVersion || paramVerbose) {
|
210 | logger.log(packageJson.name + ' version: ' + packageJson.version);
|
211 | logger.log('Node JS version: ' + nodeVersion);
|
212 | if (paramVersion) {
|
213 | process.exit(0);
|
214 | }
|
215 | }
|
216 |
|
217 | var configFile = null;
|
218 |
|
219 | configFile = argv.config;
|
220 | if (!configFile) {
|
221 | if (fs.existsSync(path.resolve(cwd, 'copy-files-from-to.cjson'))) {
|
222 | configFile = 'copy-files-from-to.cjson';
|
223 | } else if (fs.existsSync(path.resolve(cwd, 'copy-files-from-to.json'))) {
|
224 | configFile = 'copy-files-from-to.json';
|
225 | } else {
|
226 | logger.error(
|
227 | '\n' +
|
228 | chalk.bold('Error:') + ' Please ensure that you have passed correct arguments. Exiting with error (code 1).'
|
229 | );
|
230 | showHelp();
|
231 | process.exit(1);
|
232 | }
|
233 | }
|
234 |
|
235 | var configFileSource,
|
236 | configFileSourceDirectory;
|
237 |
|
238 | if (configFile.indexOf('/') === 0 || configFile.indexOf('\\') === 0) {
|
239 | configFileSource = configFile;
|
240 | } else {
|
241 | configFileSource = path.resolve(cwd, configFile);
|
242 | }
|
243 | configFileSourceDirectory = path.dirname(configFileSource);
|
244 |
|
245 | var cjsonText;
|
246 | try {
|
247 | logger.info('Reading copy instructions from file ' + utils.getRelativePath(cwd, configFileSource));
|
248 | cjsonText = fs.readFileSync(configFileSource, 'utf8');
|
249 | cjsonText = utils.stripBom(cjsonText);
|
250 | } catch (e) {
|
251 | utils.exitWithError(e, 'Error in reading file: ' + configFileSource);
|
252 | }
|
253 |
|
254 | var copyFiles = [],
|
255 | settings = {};
|
256 | try {
|
257 | var cjsonData = cjson.parse(cjsonText);
|
258 | if (cjsonData instanceof Object) {
|
259 | if (Array.isArray(cjsonData.copyFiles)) {
|
260 | copyFiles = cjsonData.copyFiles;
|
261 | }
|
262 | if (cjsonData.settings instanceof Object) {
|
263 | settings = cjsonData.settings;
|
264 | }
|
265 | }
|
266 | } catch (e) {
|
267 | utils.exitWithError(e, 'Invalid (C)JSON data:\n ' + cjsonText.replace(/\n/g, '\n '));
|
268 | }
|
269 |
|
270 |
|
271 | copyFiles = (function (copyFiles) {
|
272 | var copyFilesWithOnly = [];
|
273 |
|
274 | copyFiles.forEach(function (copyFile) {
|
275 | if (copyFile.only) {
|
276 | copyFilesWithOnly.push(copyFile);
|
277 | }
|
278 | });
|
279 |
|
280 | if (copyFilesWithOnly.length) {
|
281 | return copyFilesWithOnly;
|
282 | } else {
|
283 | return copyFiles;
|
284 | }
|
285 | }(copyFiles));
|
286 |
|
287 | if (paramOutdated) {
|
288 | var arrFromAndLatest = [];
|
289 |
|
290 | for (var i = 0; i < copyFiles.length; i++) {
|
291 | let copyFile = copyFiles[i];
|
292 | let from = copyFile.from;
|
293 | if (from && typeof from === 'object') {
|
294 | let modes = Object.keys(from);
|
295 | for (let i = 0; i < modes.length; i++) {
|
296 | let mode = modes[i],
|
297 | fromMode = from[mode];
|
298 | if (fromMode.src && fromMode.latest) {
|
299 | var ob = {
|
300 | src: fromMode.src,
|
301 | latest: fromMode.latest
|
302 | };
|
303 | arrFromAndLatest.push(ob);
|
304 | }
|
305 | }
|
306 | }
|
307 | }
|
308 |
|
309 | if (paramVerbose) {
|
310 | logger.verbose('Need to check for updates for the following entries:');
|
311 | logger.verbose(JSON.stringify(arrFromAndLatest, null, ' '));
|
312 | }
|
313 |
|
314 | var compareSrcAndLatest = function (arrSrcAndLatest) {
|
315 | async.eachLimit(
|
316 | arrSrcAndLatest,
|
317 | 8,
|
318 | function (srcAndLatest, callback) {
|
319 | var resourceSrc = srcAndLatest.src,
|
320 | resourceSrcContents = null;
|
321 | var resourceLatest = srcAndLatest.latest,
|
322 | resourceLatestContents = null;
|
323 |
|
324 | async.parallel(
|
325 | [
|
326 | function (cb) {
|
327 | utils.readContents(resourceSrc, function (err, contents, encoding) {
|
328 | if (err) {
|
329 | logger.error(' ✗ Could not read: ' + resourceSrc);
|
330 | } else {
|
331 | if (encoding === 'binary')
|
332 | resourceSrcContents = md5(contents);
|
333 | else
|
334 | resourceSrcContents = contents;
|
335 | }
|
336 | cb();
|
337 | });
|
338 | },
|
339 | function (cb) {
|
340 | utils.readContents(resourceLatest, function (err, contents, encoding) {
|
341 | if (err) {
|
342 | logger.error(' ✗ (Could not read) ' + chalk.gray(resourceLatest));
|
343 | } else {
|
344 | if (encoding === 'binary')
|
345 | resourceLatestContents = md5(contents);
|
346 | else
|
347 | resourceLatestContents = contents;
|
348 | }
|
349 | cb();
|
350 | });
|
351 | }
|
352 | ],
|
353 | function () {
|
354 | if (resourceSrcContents !== null && resourceLatestContents !== null) {
|
355 | if (resourceSrcContents === resourceLatestContents) {
|
356 | logger.success(' ✓' + chalk.gray(' (Up to date) ' + resourceSrc));
|
357 | } else {
|
358 | logger.warn(' 🔃 ("src" is outdated w.r.t. "latest") ' + chalk.gray(resourceSrc));
|
359 | }
|
360 | }
|
361 | callback();
|
362 | }
|
363 | );
|
364 | }
|
365 | );
|
366 | };
|
367 |
|
368 | if (arrFromAndLatest.length) {
|
369 | compareSrcAndLatest(arrFromAndLatest);
|
370 | } else {
|
371 | logger.warn('There are no "from" entries for which "from.<mode>.src" file needs to be compared with "from.<mode>.latest" file.');
|
372 | }
|
373 | } else {
|
374 | var WHEN_FILE_EXISTS_NOTIFY_ABOUT_AVAILABLE_CHANGE = 'notify-about-available-change',
|
375 | WHEN_FILE_EXISTS_OVERWRITE = 'overwrite',
|
376 | WHEN_FILE_EXISTS_DO_NOTHING = 'do-nothing',
|
377 | ARR_WHEN_FILE_EXISTS = [
|
378 | WHEN_FILE_EXISTS_NOTIFY_ABOUT_AVAILABLE_CHANGE,
|
379 | WHEN_FILE_EXISTS_OVERWRITE,
|
380 | WHEN_FILE_EXISTS_DO_NOTHING
|
381 | ];
|
382 | var whenFileExists = paramWhenFileExists;
|
383 | if (ARR_WHEN_FILE_EXISTS.indexOf(whenFileExists) === -1) {
|
384 | whenFileExists = settings.whenFileExists;
|
385 | if (ARR_WHEN_FILE_EXISTS.indexOf(whenFileExists) === -1) {
|
386 | whenFileExists = WHEN_FILE_EXISTS_DO_NOTHING;
|
387 | }
|
388 | }
|
389 | var overwriteIfFileAlreadyExists = (whenFileExists === WHEN_FILE_EXISTS_OVERWRITE),
|
390 | notifyAboutAvailableChange = (whenFileExists === WHEN_FILE_EXISTS_NOTIFY_ABOUT_AVAILABLE_CHANGE);
|
391 |
|
392 | var mode = argv.mode || 'default';
|
393 |
|
394 | var warningsEncountered = 0;
|
395 |
|
396 | copyFiles = copyFiles.map(function normalizeData(copyFile) {
|
397 | var latest = null;
|
398 | var from = null,
|
399 | skipFrom = null;
|
400 | if (typeof copyFile.from === 'string' || Array.isArray(copyFile.from)) {
|
401 | from = copyFile.from;
|
402 | } else {
|
403 | var fromMode = copyFile.from[mode] || copyFile.from['default'] || {};
|
404 | if (typeof fromMode === 'string') {
|
405 | from = fromMode;
|
406 | } else {
|
407 | from = fromMode.src;
|
408 | skipFrom = !!fromMode.skip;
|
409 | latest = fromMode.latest;
|
410 | }
|
411 | }
|
412 |
|
413 | var to = null,
|
414 | skipTo = null,
|
415 | uglify = null;
|
416 | if (typeof copyFile.to === 'string') {
|
417 | to = copyFile.to;
|
418 | } else {
|
419 | var toMode = copyFile.to[mode] || copyFile.to['default'] || {};
|
420 | if (typeof toMode === 'string') {
|
421 | to = toMode;
|
422 | } else {
|
423 | to = toMode.dest;
|
424 | skipTo = !!toMode.skip;
|
425 | }
|
426 |
|
427 | if (typeof toMode === 'object' && toMode.uglifyJs !== undefined) {
|
428 | uglify = utils.booleanIntention(toMode.uglifyJs, false);
|
429 | } else {
|
430 | uglify = utils.booleanIntention(settings.uglifyJs, false);
|
431 | }
|
432 | }
|
433 |
|
434 | if (isGlob(to)) {
|
435 | warningsEncountered++;
|
436 | logger.log('');
|
437 | logger.warn('The "to" entries should not be a "glob" pattern. ' + chalk.blue('(Reference: https://github.com/isaacs/node-glob#glob-primer)'));
|
438 |
|
439 | to = null;
|
440 | }
|
441 |
|
442 | let toFlat = null;
|
443 | if (copyFile.toFlat) {
|
444 | toFlat = true;
|
445 | }
|
446 |
|
447 | if ((typeof from === 'string' || Array.isArray(from)) && typeof to === 'string') {
|
448 | if (!Array.isArray(from) && (from.match(/\.js$/) || to.match(/\.js$/))) {
|
449 |
|
450 |
|
451 |
|
452 | } else {
|
453 |
|
454 | uglify = false;
|
455 | }
|
456 |
|
457 | return {
|
458 | intendedFrom: from,
|
459 | intendedTo: to,
|
460 | latest: latest,
|
461 | from: (function () {
|
462 | if (utils.isRemoteResource(from)) {
|
463 | return from;
|
464 | }
|
465 | if (Array.isArray(from)) {
|
466 |
|
467 | let globPatterns = [];
|
468 | let globSettings = {};
|
469 | from.forEach( globPart => {
|
470 | if (typeof globPart === 'string') {
|
471 | if (globPart.charAt(0) === '!')
|
472 | globPatterns.push('!' + path.join(configFileSourceDirectory, globPart.substring(1)));
|
473 | else
|
474 | globPatterns.push(path.join(configFileSourceDirectory, globPart));
|
475 | } else {
|
476 | Object.assign(globSettings, globPart);
|
477 | }
|
478 | });
|
479 | return {
|
480 | globPatterns: globPatterns,
|
481 | globSettings: globSettings,
|
482 | };
|
483 | }
|
484 | return path.join(configFileSourceDirectory, from);
|
485 | }()),
|
486 | to: path.join(configFileSourceDirectory, to),
|
487 | toFlat: toFlat,
|
488 | uglify: uglify
|
489 | };
|
490 | } else {
|
491 | if (
|
492 | (typeof from !== 'string' && !skipFrom) ||
|
493 | (typeof to !== 'string' && !skipTo)
|
494 | ) {
|
495 | warningsEncountered++;
|
496 | if (warningsEncountered === 1) {
|
497 | logger.log('');
|
498 | logger.warn('Some entries will not be considered in the current mode (' + mode + ').');
|
499 | }
|
500 |
|
501 | logger.log('');
|
502 |
|
503 | var applicableModesForSkip = _.uniq(['"default"', '"' + mode + '"']).join(' / ');
|
504 | if (typeof from !== 'string' && !skipFrom) {
|
505 | var fromValuesToCheck = _.uniq([
|
506 | '"from"',
|
507 | '"from.default"',
|
508 | '"from.default.src"',
|
509 | '"from.' + mode + '"',
|
510 | '"from.' + mode + '.src"'
|
511 | ]).join(' / ');
|
512 | logger.warn(' Please ensure that the value for ' + fromValuesToCheck + ' is a string.');
|
513 | logger.warn(' Otherwise, add ' + chalk.blue('"skip": true') + ' under "from" for mode: ' + applicableModesForSkip);
|
514 | }
|
515 | if (typeof to !== 'string' && !skipTo) {
|
516 | var toValuesToCheck = _.uniq([
|
517 | '"to"',
|
518 | '"to.default"',
|
519 | '"to.default.dest"',
|
520 | '"to.' + mode + '"',
|
521 | '"to.' + mode + '.dest"'
|
522 | ]).join(' / ');
|
523 | logger.warn(' Please ensure that the value for ' + toValuesToCheck + ' is a string.');
|
524 | logger.warn(' Otherwise, add ' + chalk.blue('"skip": true') + ' under "to" for mode: ' + applicableModesForSkip);
|
525 | }
|
526 |
|
527 | logger.warn(' ' + JSON.stringify(copyFile, null, ' ').replace(/\n/g, '\n '));
|
528 | }
|
529 | }
|
530 | });
|
531 |
|
532 | copyFiles = (function () {
|
533 | var arr = [];
|
534 | copyFiles.forEach(function (copyFile) {
|
535 | if (copyFile && copyFile.from) {
|
536 | const entries = function() {
|
537 | if (typeof copyFile.from === 'string' && isGlob(copyFile.from)) {
|
538 | return fastGlob.sync([copyFile.from], { dot: !settings.ignoreDotFilesAndFolders });
|
539 | } else if (copyFile.from.globPatterns) {
|
540 | return fastGlob.sync(
|
541 | copyFile.from.globPatterns,
|
542 | Object.assign({ dot: !settings.ignoreDotFilesAndFolders }, copyFile.from.globSettings)
|
543 | );
|
544 | } else {
|
545 | return null;
|
546 | }
|
547 | }();
|
548 | if (entries && entries.length) {
|
549 | entries.forEach(function (entry) {
|
550 | var ob = JSON.parse(JSON.stringify(copyFile));
|
551 | ob.from = entry;
|
552 | const entryPoint = entry.substring(configFileSourceDirectory.length+1);
|
553 | let targetTo = entryPoint.substring(entryPoint.indexOf('/'));
|
554 | if (copyFile.toFlat) {
|
555 | const fileName = path.basename(targetTo);
|
556 | targetTo = fileName;
|
557 | }
|
558 |
|
559 | ob.to = path.join(
|
560 | ob.to,
|
561 | targetTo
|
562 | );
|
563 | arr.push(ob);
|
564 | });
|
565 | } else {
|
566 | arr.push(copyFile);
|
567 | }
|
568 | }
|
569 | });
|
570 | return arr;
|
571 | }());
|
572 |
|
573 | var writeContents = function (copyFile, options, cb) {
|
574 | var to = copyFile.to,
|
575 | intendedFrom = copyFile.intendedFrom;
|
576 | var contents = options.contents,
|
577 | uglified = options.uglified,
|
578 | overwriteIfFileAlreadyExists = options.overwriteIfFileAlreadyExists;
|
579 |
|
580 | utils.ensureDirectoryExistence(to);
|
581 |
|
582 | var fileExists = fs.existsSync(to),
|
583 | fileDoesNotExist = !fileExists;
|
584 |
|
585 | var avoidedFileOverwrite;
|
586 | let finalPath = '';
|
587 | if (
|
588 | fileDoesNotExist ||
|
589 | (fileExists && overwriteIfFileAlreadyExists)
|
590 | ) {
|
591 | try {
|
592 | if (to[to.length-1] === '/') {
|
593 | const stats = fs.statSync(to);
|
594 | if (stats.isDirectory()) {
|
595 | if (typeof intendedFrom === 'string' && !isGlob(intendedFrom)) {
|
596 | const fileName = path.basename(intendedFrom);
|
597 | to = path.join(to, fileName);
|
598 | }
|
599 | }
|
600 | }
|
601 |
|
602 | fs.writeFileSync(to, contents, copyFile.encoding === 'binary' ? null : 'utf8');
|
603 | finalPath = to;
|
604 | } catch (e) {
|
605 | cb(e);
|
606 | return;
|
607 | }
|
608 | if (settings.addReferenceToSourceOfOrigin) {
|
609 | var sourceDetails = intendedFrom;
|
610 | if (uglified) {
|
611 | sourceDetails += (uglified.uglifyCommand || '');
|
612 | }
|
613 |
|
614 | |
615 |
|
616 |
|
617 |
|
618 |
|
619 |
|
620 | fs.writeFileSync(to + '.source.txt', sourceDetails, 'utf8');
|
621 | }
|
622 | avoidedFileOverwrite = false;
|
623 | } else {
|
624 | avoidedFileOverwrite = true;
|
625 | }
|
626 | cb(null, avoidedFileOverwrite, finalPath || to);
|
627 | };
|
628 |
|
629 | var checkForAvailableChange = function (copyFile, contentsOfFrom, config, cb) {
|
630 | var notifyAboutAvailableChange = config.notifyAboutAvailableChange;
|
631 |
|
632 | if (notifyAboutAvailableChange) {
|
633 | var to = copyFile.to;
|
634 | utils.readContents(to, function (err, contentsOfTo, encoding) {
|
635 | if (err) {
|
636 | cb(chalk.red(' (unable to read "to.<mode>.dest" file at path ' + to + ')'));
|
637 | warningsEncountered++;
|
638 | } else {
|
639 | copyFile.encoding = encoding;
|
640 | var needsUglify = copyFile.uglify;
|
641 |
|
642 | utils.doUglify(needsUglify, contentsOfFrom, function (processedCode) {
|
643 | if (copyFile.encoding === 'binary') {
|
644 |
|
645 | if (md5(processedCode) === md5(contentsOfTo)) {
|
646 | cb(chalk.gray(' (up to date)'));
|
647 | } else {
|
648 | cb(chalk.yellow(' (md5 update is available)'));
|
649 | }
|
650 | } else {
|
651 | if (processedCode === contentsOfTo) {
|
652 | cb(chalk.gray(' (up to date)'));
|
653 | } else {
|
654 | cb(chalk.yellow(' (update is available)'));
|
655 | }
|
656 | }
|
657 | });
|
658 | }
|
659 | });
|
660 | } else {
|
661 | cb();
|
662 | }
|
663 | };
|
664 |
|
665 | var preWriteOperations = function (copyFile, contents, cb) {
|
666 | var needsUglify = copyFile.uglify;
|
667 | utils.doUglify(needsUglify, contents, function (processedCode, consoleCommand) {
|
668 | if (needsUglify) {
|
669 | cb({
|
670 | contentsAfterPreWriteOperations: processedCode,
|
671 | uglified: {
|
672 | uglifyCommand:
|
673 | '\n' +
|
674 | '\n' +
|
675 | '$ ' + consoleCommand +
|
676 | '\n' +
|
677 | '\nWhere:' +
|
678 | '\n uglifyjs = npm install -g uglify-js@' + packageJson.dependencies['uglify-js'] +
|
679 | '\n <source> = File ' + copyFile.intendedFrom +
|
680 | '\n <destination> = File ./' + path.basename(copyFile.intendedTo)
|
681 | }
|
682 | });
|
683 | } else {
|
684 | cb({
|
685 | contentsAfterPreWriteOperations: processedCode
|
686 | });
|
687 | }
|
688 | });
|
689 | };
|
690 |
|
691 | var postWriteOperations = function (copyFile, originalContents, contentsAfterPreWriteOperations, config, cb) {
|
692 | checkForAvailableChange(copyFile, originalContents, config, function (status) {
|
693 | cb(status);
|
694 | });
|
695 | };
|
696 |
|
697 | var doCopyFile = function (copyFile, cb) {
|
698 | var from = copyFile.from,
|
699 | to = copyFile.to;
|
700 |
|
701 | var printFrom = ' ' + chalk.gray(utils.getRelativePath(cwd, from));
|
702 | var printFromToOriginal = ' ' + chalk.gray(utils.getRelativePath(cwd, to));
|
703 |
|
704 | var successMessage = ' ' + chalk.green('✓') + ` Copied `,
|
705 | successMessageAvoidedFileOverwrite = ' ' + chalk.green('✓') + chalk.gray(' Already exists'),
|
706 | errorMessageCouldNotReadFromSrc = ' ' + chalk.red('✗') + ' Could not read',
|
707 | errorMessageFailedToCopy = ' ' + chalk.red('✗') + ' Failed to copy';
|
708 |
|
709 | var destFileExists = fs.existsSync(to),
|
710 | destFileDoesNotExist = !destFileExists;
|
711 | if (
|
712 | destFileDoesNotExist ||
|
713 | (
|
714 | destFileExists &&
|
715 | (
|
716 | overwriteIfFileAlreadyExists ||
|
717 | notifyAboutAvailableChange
|
718 | )
|
719 | )
|
720 | ) {
|
721 | utils.readContents(copyFile.from, function (err, contentsOfFrom, encoding) {
|
722 | if (err) {
|
723 | warningsEncountered++;
|
724 | if (destFileExists && notifyAboutAvailableChange) {
|
725 | logger.log(errorMessageCouldNotReadFromSrc + printFrom);
|
726 | } else {
|
727 | logger.log(errorMessageFailedToCopy + printFromToOriginal);
|
728 | }
|
729 | cb();
|
730 | return;
|
731 | }
|
732 | copyFile.encoding = encoding;
|
733 | var typeString = `[${utils.getColoredTypeString(encoding)}]`;
|
734 |
|
735 | preWriteOperations(copyFile, contentsOfFrom, function (options) {
|
736 | var contentsAfterPreWriteOperations = options.contentsAfterPreWriteOperations,
|
737 | uglified = options.uglified;
|
738 | writeContents(
|
739 | copyFile,
|
740 | {
|
741 | contents: contentsAfterPreWriteOperations,
|
742 | uglified: uglified,
|
743 | overwriteIfFileAlreadyExists: overwriteIfFileAlreadyExists
|
744 | },
|
745 | function (err, avoidedFileOverwrite, finalPath) {
|
746 | if (err) {
|
747 | warningsEncountered++;
|
748 | logger.log(errorMessageFailedToCopy + printFromTo);
|
749 | cb();
|
750 | return;
|
751 | } else {
|
752 | var printTo = ' ' + chalk.gray(utils.getRelativePath(cwd, finalPath));
|
753 | var printFromTo = printFrom + ' to' + printTo;
|
754 |
|
755 | postWriteOperations(
|
756 | copyFile,
|
757 | contentsOfFrom,
|
758 | contentsAfterPreWriteOperations,
|
759 | {
|
760 | notifyAboutAvailableChange: notifyAboutAvailableChange
|
761 | },
|
762 | function (appendToSuccessMessage) {
|
763 | if (avoidedFileOverwrite) {
|
764 | logger.log(successMessageAvoidedFileOverwrite + (appendToSuccessMessage || '') + printTo);
|
765 | } else {
|
766 |
|
767 |
|
768 | let destFileDidNotExist = destFileDoesNotExist;
|
769 | if (destFileDidNotExist) {
|
770 | logger.log(successMessage + typeString + printFromTo);
|
771 | } else {
|
772 | logger.log(successMessage + typeString + (appendToSuccessMessage || '') + printFromTo);
|
773 | }
|
774 | }
|
775 | cb();
|
776 | }
|
777 | );
|
778 | }
|
779 | }
|
780 | );
|
781 | });
|
782 | });
|
783 | } else {
|
784 | logger.log(successMessageAvoidedFileOverwrite + printFromToOriginal);
|
785 | cb();
|
786 | }
|
787 | };
|
788 |
|
789 | var done = function (warningsEncountered) {
|
790 | if (warningsEncountered) {
|
791 | if (warningsEncountered === 1) {
|
792 | logger.warn('\nEncountered ' + warningsEncountered + ' warning. Please check.');
|
793 | } else {
|
794 | logger.warn('\nEncountered ' + warningsEncountered + ' warnings. Please check.');
|
795 | }
|
796 | logger.error('Error: Please resolve the above mentioned warnings. Exiting with code 1.');
|
797 | process.exit(1);
|
798 | }
|
799 | };
|
800 |
|
801 | if (copyFiles.length) {
|
802 | logger.log(
|
803 | chalk.blue('\nStarting copy operation in "' + (mode || 'default') + '" mode:') +
|
804 | (overwriteIfFileAlreadyExists ? chalk.yellow(' (overwrite option is on)') : '')
|
805 | );
|
806 |
|
807 | async.eachLimit(
|
808 | copyFiles,
|
809 | 8,
|
810 | function (copyFile, callback) {
|
811 |
|
812 |
|
813 | if (copyFile && typeof copyFile === 'object') {
|
814 | doCopyFile(copyFile, function () {
|
815 | callback();
|
816 | });
|
817 | } else {
|
818 | callback();
|
819 | }
|
820 | },
|
821 | function () {
|
822 | done(warningsEncountered);
|
823 | }
|
824 | );
|
825 | } else {
|
826 | logger.warn('No instructions applicable for copy operation.');
|
827 | }
|
828 | }
|
829 | }
|