Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,11 @@ Returns true if file.contents is a Stream.

Returns true if file.contents is null.

### clone()
### clone([opt])

Returns a new File object with all attributes cloned. Custom attributes are deep-cloned.
Returns a new File object with all attributes cloned. Custom attributes are deep-cloned by default.

If opt.isDeep is false, a shallow clone will be performed.

### pipe(stream[, opt])

Expand Down
9 changes: 6 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ var path = require('path');

var cloneStats = require('clone-stats');
var _ = require('lodash');
var cloneDeep = _.cloneDeep;
var cloneShallow = _.clone;

var isBuffer = require('./lib/isBuffer');
var isStream = require('./lib/isStream');
Expand Down Expand Up @@ -44,12 +44,15 @@ File.prototype.isDirectory = function() {
return this.isNull() && this.stat && this.stat.isDirectory();
};

File.prototype.clone = function() {
File.prototype.clone = function(opt) {
if (!opt) opt = {};
if (typeof opt.isDeep === 'undefined') opt.isDeep = true;

var clone = new File();

Object.keys(this).forEach(function(key) {
if (key !== '_contents' && key !== 'stat') {
clone[key] = cloneDeep(this[key]);
clone[key] = cloneShallow(this[key], opt.isDeep);
}
}, this);

Expand Down
22 changes: 21 additions & 1 deletion test/File.js
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ describe('File', function() {

done();
});

it('should copy custom properties', function(done) {
var options = {
cwd: "/",
Expand All @@ -270,7 +270,27 @@ describe('File', function() {
file2.base.should.equal(file.base);
file2.path.should.equal(file.path);
file2.custom.should.not.equal(file.custom);

done();
});

it('should support shallow cloning of custom properties', function(done) {
var options = {
cwd: "/",
base: "/test/",
path: "/test/test.coffee",
contents: null
};

var file = new File(options);
file.custom = { a: { b: 'custom property' } };

var file2 = file.clone({ isDeep: false });

file2.should.not.equal(file, 'refs should be different');
file2.custom.should.not.equal(file.custom);
file2.custom.a.should.equal(file.custom.a);
file2.custom.a.b.should.equal(file.custom.a.b);

done();
});
Expand Down