-
-
Notifications
You must be signed in to change notification settings - Fork 302
/
Copy pathactions.js
511 lines (424 loc) · 13.6 KB
/
actions.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
var logger = process.logging || require('../util/log');
var log = logger('generators:action');
var fs = require('fs');
var path = require('path');
var events = require('events');
var mkdirp = require('mkdirp');
var isBinaryFile = require('isbinaryfile');
var rimraf = require('rimraf');
var async = require('async');
var iconv = require('iconv-lite');
var chalk = require('chalk');
var actions = module.exports;
actions.log = log;
/**
* Stores and return the source root for this class. The source root is used to
* prefix filepath with `.read()` or `.template()`.
*
* @param {String} root
*/
actions.sourceRoot = function sourceRoot(root) {
if (root) {
this._sourceRoot = path.resolve(root);
}
return this._sourceRoot;
};
/**
* Sets the destination root for this class, the working directory. Relative
* path are added to the directory where the script was invoked and
* expanded.
*
* This automatically creates the working directory if it doensn't exists and
* `cd` into it.
*
* @param {String} root
*/
actions.destinationRoot = function destinationRoot(root) {
if (root) {
this._destinationRoot = path.resolve(root);
if (!fs.existsSync(root)) {
this.mkdir(root);
}
process.chdir(root);
}
return this._destinationRoot || './';
};
/**
* Stores and return the cache root for this class. The cache root is used to
* `git clone` repositories from github by `.remote()` for example.
*/
actions.cacheRoot = function cacheRoot() {
// we follow XDG specs if possible:
// http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
if (process.env.XDG_CACHE_HOME) {
return path.join(process.env.XDG_CACHE_HOME, 'yeoman');
}
// otherwise, we fallback to a temp dir in the home
var home = process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME'];
return path.join(home, '.cache/yeoman');
};
// Copy helper for two versions of copy action
function prepCopy(source, destination, process) {
var body;
destination = destination || source;
if (typeof destination === 'function') {
process = destination;
destination = source;
}
source = this.isPathAbsolute(source) ? source : path.join(this.sourceRoot(), source);
var encoding = null;
var binary = isBinaryFile(source);
if (!binary) {
encoding = 'utf8';
}
body = fs.readFileSync(source, encoding);
if (typeof process === 'function' && !binary) {
body = process(body, source, destination, {
encoding: encoding
});
}
return {
body: body,
encoding: encoding,
destination: destination,
source: source
};
};
/**
* Make some of the file API aware of our source/destination root paths.
* `copy`, `template` (only when could be applied/required by legacy code),
* `write` and alike consider.
*
* @param {String} source
* @param {String} destination
* @param {Function} process
*/
actions.copy = function copy(source, destination, process) {
var file = prepCopy.call(this, source, destination, process);
try {
file.body = this.engine(file.body, this);
} catch (err) {
// this happens in some cases when trying to copy a JS file like lodash/underscore
// (conflicting the templating engine)
}
this.checkForCollision(file.destination, file.body, function (err, config) {
var stats;
if (err) {
config.callback(err);
return this.emit('error', err);
}
// create or force means file write, identical or skip prevent the
// actual write.
if (!(/force|create/.test(config.status))) {
return config.callback();
}
mkdirp.sync(path.dirname(file.destination));
fs.writeFileSync(file.destination, file.body);
// synchronize stats and modification times from the original file.
stats = fs.statSync(file.source);
try {
fs.chmodSync(file.destination, stats.mode);
fs.utimesSync(file.destination, stats.atime, stats.mtime);
} catch (err) {
this.log.error('Error setting permissions of "' + chalk.bold(file.destination) + '" file: ' + err);
}
config.callback();
}.bind(this));
return this;
};
/**
* Bulk copy
* https://github.com/yeoman/generator/pull/359
* https://github.com/yeoman/generator/issues/350
*
* An optimized copy method for larger file trees. Does not do
* full conflicter checks, only check ir root directory is not empty.
*
* @param {String} source
* @param {String} destination
* @param {Function} process
*/
actions.bulkCopy = function bulkCopy(source, destination, process) {
var file = prepCopy.call(this, source, destination, process);
mkdirp.sync(path.dirname(file.destination));
fs.writeFileSync(file.destination, file.body);
// synchronize stats and modification times from the original file.
stats = fs.statSync(file.source);
try {
fs.chmodSync(file.destination, stats.mode);
fs.utimesSync(file.destination, stats.atime, stats.mtime);
} catch (err) {
this.log.error('Error setting permissions of "' + chalk.bold(file.destination) + '" file: ' + err);
}
log.create(file.destination);
return this;
};
/**
* A simple method to read the content of the a file borrowed from Grunt:
* https://github.com/gruntjs/grunt/blob/master/lib/grunt/file.js
*
* Discussion and future plans:
* https://github.com/yeoman/generator/pull/220
*
* The encoding is `utf8` by default, to read binary files, pass the proper
* encoding or null. Non absolute path are prefixed by the source root.
*
* @param {String} filepath
* @param {String} encoding
*/
actions.read = function read(filepath, encoding) {
var contents;
if (!this.isPathAbsolute(filepath)) {
filepath = path.join(this.sourceRoot(), filepath);
}
try {
contents = fs.readFileSync(String(filepath));
// if encoding is not explicitly null, convert from encoded buffer to a
// string. if no encoding was specified, use the default.
if (encoding !== null) {
contents = iconv.decode(contents, encoding || 'utf8');
// strip any BOM that might exist.
if (contents.charCodeAt(0) === 0xFEFF) {
contents = contents.substring(1);
}
}
return contents;
} catch (e) {
throw new Error('Unable to read "' + filepath + '" file (Error code: ' + e.code + ').');
}
};
/**
* Writes a chunk of data to a given `filepath`, checking for collision prior
* to the file write.
*
* @param {String} filepath
* @param {String} content
*/
actions.write = function write(filepath, content) {
this.checkForCollision(filepath, content, function (err, config) {
if (err) {
config.callback(err);
return this.emit('error', err);
}
// create or force means file write, identical or skip prevent the
// actual write
if (/force|create/.test(config.status)) {
mkdirp.sync(path.dirname(filepath));
fs.writeFileSync(filepath, content);
}
config.callback();
});
return this;
};
/**
* File collision checked. Takes a `filepath` (the file about to be written)
* and the actual content. A basic check is done to see if the file exists, if
* it does:
*
* 1. Read its content from `fs`
* 2. Compare it with the provided content
* 3. If identical, mark it as is and skip the check
* 4. If diverged, prepare and show up the file collision menu
*
* The menu has the following options:
*
* - `Y` Yes, overwrite
* - `n` No, do not overwrite
* - `a` All, overwrite this and all others
* - `q` Quit, abort
* - `d` Diff, show the differences between the old and the new
* - `h` Help, show this help
*
* @param {String} filepath
* @param {String} content
* @param {Function} cb
*/
actions.checkForCollision = function checkForCollision(filepath, content, cb) {
this.conflicter.add({
file: filepath,
content: content
});
this.conflicter.once('resolved:' + filepath, cb.bind(this, null));
};
/**
* Gets a template at the relative source, executes it and makes a copy
* at the relative destination. If the destination is not given it's assumed
* to be equal to the source relative to destination.
*
* Use configured engine to render the provided `source` template at the given
* `destination`. `data` is an optional hash to pass to the template, if
* undefined, executes the template in the generator instance context.
*
* @param {String} source
* @param {String} destination
* @param {Object} data
*/
actions.template = function template(source, destination, data) {
data = data || this;
destination = destination || source;
var body = this.read(source, 'utf8');
body = this.engine(body, data);
this.write(destination, body);
return this;
};
/**
* The engine method is the function used whenever a template needs to be rendered.
*
* It uses the configured engine (default: underscore) to render the `body`
* template with the provided `data`.
*
* @param {String} body
* @param {Object} data
*/
actions.engine = function engine(body, data) {
if (!this._engine) {
throw new Error('Trying to render template without valid engine.');
}
return this._engine.detect && this._engine.detect(body) ?
this._engine(body, data) :
body;
};
// Shared directory method
function _directory(source, destination, process, bulk) {
// Only add sourceRoot if the path is not absolute
var root = this.isPathAbsolute(source) ? source : path.join(this.sourceRoot(), source);
var files = this.expandFiles('**', { dot: true, cwd: root });
destination = destination || source;
if (typeof destination === 'function') {
process = destination;
destination = source;
}
var cp = this.copy;
if (bulk) {
cp = this.bulkCopy;
}
// get the path relative to the template root, and copy to the relative destination
for (var i in files) {
var dest = path.join(destination, files[i]);
cp.call(this, path.join(root, files[i]), dest, process);
}
return this;
};
/**
* Copies recursively the files from source directory to root directory.
*
* @param {String} source
* @param {String} destination
* @param {Function} process
*/
actions.directory = function directory(source, destination, process) {
return _directory.call(this, source, destination, process);
};
/**
* Copies recursively the files from source directory to root directory.
*
* @param {String} source
* @param {String} destination
* @param {Function} process
*/
actions.bulkDirectory = function directory(source, destination, process) {
var self = this;
// Join the source here because the conflicter will not run
// until next tick, which resets the source root on remote
// bulkCopy operations
source = path.join(this.sourceRoot(), source);
this.checkForCollision(destination, null, function (err, config) {
// create or force means file write, identical or skip prevent the
// actual write.
if (!(/force|create/.test(config.status))) {
return config.callback();
}
_directory.call(this, source, destination, process, true);
config.callback();
});
return this;
};
/**
* Remotely fetch a package on github, store this into a _cache folder, and
* provide a "remote" object as a facade API to ourself (part of genrator API,
* copy, template, directory). It's possible to remove local cache, and force
* a new remote fetch of the package on Github.
*
* ### Examples:
*
* this.remote('user', 'repo', function(err, remote) {
* remote.copy('.', 'vendors/user-repo');
* });
*
* @param {String} username
* @param {String} repo
* @param {String} branch
* @param {Function} cb
* @param {Boolean} refresh
*/
actions.remote = function (username, repo, branch, cb, refresh) {
if (!cb) {
cb = branch;
branch = 'master';
}
var self = this;
var cache = path.join(this.cacheRoot(), username, repo, branch);
var url = 'http://github.com/' + [username, repo, 'archive', branch].join('/') + '.tar.gz';
fs.stat(cache, function (err) {
// already cached
if (!err) {
// no refresh, so we can use this cache
if (!refresh) {
return done();
}
// otherwise, we need to remove it, to fetch it again
rimraf(cache, function (err) {
if (err) {
return cb(err);
}
self.tarball(url, cache, done);
});
} else {
self.tarball(url, cache, done);
}
});
function done(err) {
if (err) {
return cb(err);
}
var files = self.expandFiles('**', { cwd: cache, dot: true });
var remote = {};
remote.cachePath = cache;
// simple proxy to `.copy(source, destination)`
remote.copy = function copy(source, destination) {
source = path.join(cache, source);
self.copy(source, destination);
return this;
};
// simple proxy to `.bulkCopy(source, destination)`
remote.bulkCopy = function copy(source, destination) {
source = path.join(cache, source);
self.bulkCopy(source, destination);
return this;
};
// same as `.template(source, destination, data)`
remote.template = function template(source, destination, data) {
data = data || self;
destination = destination || source;
source = path.join(cache, source);
var body = self.engine(self.read(source), data);
self.write(destination, body);
};
// same as `.template(source, destination)`
remote.directory = function directory(source, destination) {
var root = self.sourceRoot();
self.sourceRoot(cache);
self.directory(source, destination);
self.sourceRoot(root);
};
// simple proxy to `.bulkDirectory(source, destination)`
remote.bulkDirectory = function directory(source, destination) {
var root = self.sourceRoot();
self.sourceRoot(cache);
self.bulkDirectory(source, destination);
self.sourceRoot(root);
};
cb(err, remote, files);
}
return this;
};