From 924c7eea147c3f6d3df775949fd76878d4ed7d67 Mon Sep 17 00:00:00 2001 From: popomore Date: Thu, 28 Aug 2014 20:09:59 +0800 Subject: [PATCH] Breaking: Add option to deep-clone properties, default to false (closes #29) --- index.js | 15 +++++++++++---- test/File.js | 36 +++++++++++++++++++++++++++++++++++- 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/index.js b/index.js index e19234e..6faa797 100644 --- a/index.js +++ b/index.js @@ -1,8 +1,7 @@ var path = require('path'); var cloneStats = require('clone-stats'); -var _ = require('lodash'); -var cloneDeep = _.cloneDeep; +var cloneDeep = require('lodash').cloneDeep; var isBuffer = require('./lib/isBuffer'); var isStream = require('./lib/isStream'); @@ -45,12 +44,20 @@ File.prototype.isDirectory = function() { return this.isNull() && this.stat && this.stat.isDirectory(); }; -File.prototype.clone = function() { +File.prototype.clone = function(opt) { + if (typeof opt === 'boolean') { + opt = { deep: opt }; + } else if (!opt) { + opt = { deep: false }; + } else { + opt.deep = opt.deep || false; + } + var clone = new File(); Object.keys(this).forEach(function(key) { if (key !== '_contents' && key !== 'stat') { - clone[key] = cloneDeep(this[key]); + clone[key] = opt.deep === true ? cloneDeep(this[key]) : this[key]; } }, this); diff --git a/test/File.js b/test/File.js index 3eed81e..58ab1d1 100644 --- a/test/File.js +++ b/test/File.js @@ -269,7 +269,7 @@ describe('File', function() { file2.cwd.should.equal(file.cwd); file2.base.should.equal(file.base); file2.path.should.equal(file.path); - file2.custom.should.not.equal(file.custom); + file2.custom.should.equal(file.custom); file2.custom.a.should.equal(file.custom.a); done(); @@ -302,6 +302,40 @@ describe('File', function() { done(); }); + + it('should copy all attributes deeply', function(done) { + var options = { + cwd: '/', + base: '/test/', + path: '/test/test.coffee', + contents: null + }; + + var file = new File(options); + file.custom = { a: 'custom property' }; + + var file2 = file.clone(true); + file2.custom.should.eql(file.custom); + file2.custom.should.not.equal(file.custom); + file2.custom.a.should.equal(file.custom.a); + + var file3 = file.clone({ deep: true }); + file3.custom.should.eql(file.custom); + file3.custom.should.not.equal(file.custom); + file3.custom.a.should.equal(file.custom.a); + + var file4 = file.clone(false); + file4.custom.should.eql(file.custom); + file4.custom.should.equal(file.custom); + file4.custom.a.should.equal(file.custom.a); + + var file5 = file.clone({ deep: false }); + file5.custom.should.eql(file.custom); + file5.custom.should.equal(file.custom); + file5.custom.a.should.equal(file.custom.a); + + done(); + }); }); describe('pipe()', function() {