Skip to content

Instantly share code, notes, and snippets.

@zaius
Created April 28, 2014 08:40
Show Gist options
  • Save zaius/11365659 to your computer and use it in GitHub Desktop.
Save zaius/11365659 to your computer and use it in GitHub Desktop.
Deep hard link / copy
fs = require 'fs'
path = require 'path'
RSVP = require 'rsvp'
rimraf = require 'rimraf'
mkdirp = require 'mkdirp'
walkSync = require 'walk-sync'
# Passing in a srcDir allow us to know where the path should be relative to.
# This means we can autocreate subdirectories for all files.
exports.linkFiles = (files, srcDir, destDir) ->
new RSVP.Promise (resolve, reject) ->
for file in files
# stat follows symlinks. fstat does not. stat will follow a symlink all
# the way to the end. Circular references will throw:
# Error: ELOOP, too many symbolic links encountered
srcFile = srcDir + '/' + file
stats = fs.statSync srcFile
# Skip for now? I think no need for empty directories.
continue if stats.isDirectory()
reject "Can't copy #{file}" unless stats.isFile()
destFile = destDir + '/' + file
mkdirp.sync path.dirname(destFile)
fs.linkSync srcFile, destFile
resolve()
# Hard link a directory structure
exports.link = (srcDir, destDir) ->
rimraf.sync destDir
files = walkSync srcDir
exports.linkFiles files, srcDir, destDir
exports.copy = (srcDir, destDir) ->
new RSVP.Promise (resolve, reject) ->
ncp srcDir, destDir, stopOnErr: true, clobber: true, (err) ->
if err
console.log "Copy error".red, err
reject(err)
else
resolve()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment