From 83b721a579127bca0041e0eed1e087121134620f Mon Sep 17 00:00:00 2001 From: Jannon Date: Fri, 10 Feb 2012 16:16:08 -0800 Subject: [PATCH] Make copy friendlier with option not to blow away existing dirs Let's play nice. Now when using copyDirSyncRecursive, you can pass an optional opts object. If this object contains a preserve member, then the function will preserve exisiting directories and only overwrite existing files within the directories. Without passing the option it behaves the same as always --- lib/wrench.js | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/lib/wrench.js b/lib/wrench.js index 1ddd91d..de0c235 100644 --- a/lib/wrench.js +++ b/lib/wrench.js @@ -99,17 +99,22 @@ exports.rmdirSyncRecursive = function(path, failSilent) { * * Note: Directories should be passed to this function without a trailing slash. */ -exports.copyDirSyncRecursive = function(sourceDir, newDirLocation) { - /* Copying over something is... tricky. The user should know what they're doing at this point, so... - * blow any existing directory away! - */ - try { - if(fs.statSync(newDirLocation).isDirectory()) exports.rmdirSyncRecursive(newDirLocation); - } catch(e) { } +exports.copyDirSyncRecursive = function(sourceDir, newDirLocation, opts) { + + if (!opts || !opts.preserve) { + try { + if(fs.statSync(newDirLocation).isDirectory()) exports.rmdirSyncRecursive(newDirLocation); + } catch(e) { } + } /* Create the directory where all our junk is moving to; read the mode of the source directory and mirror it */ var checkDir = fs.statSync(sourceDir); - fs.mkdirSync(newDirLocation, checkDir.mode); + try { + fs.mkdirSync(newDirLocation, checkDir.mode); + } catch (e) { + //if the directory already exists, that's okay + if (e.code !== 'EEXIST') throw e; + } var files = fs.readdirSync(sourceDir); @@ -118,7 +123,7 @@ exports.copyDirSyncRecursive = function(sourceDir, newDirLocation) { if(currFile.isDirectory()) { /* recursion this thing right on back. */ - exports.copyDirSyncRecursive(sourceDir + "/" + files[i], newDirLocation + "/" + files[i]); + exports.copyDirSyncRecursive(sourceDir + "/" + files[i], newDirLocation + "/" + files[i], opts); } else if(currFile.isSymbolicLink()) { var symlinkFull = fs.readlinkSync(sourceDir + "/" + files[i]); fs.symlinkSync(symlinkFull, newDirLocation + "/" + files[i]); -- 2.39.5