I want to sync two folders using gulp. I have managed to achieve this with the a package called gulp-directory-sync (see included task below), but now I need to exclude some files from the sync based on if the file or directory name starts with "__" (two underscores). I have tried to find a sync plugin with an ignore or exclude feature, but without success, so I am now wondering if anyone might know a workaround for this.
var gulp = require('gulp');
var dirSync = require('gulp-directory-sync');
gulp.task('sync', function () {
return gulp.src('')
.pipe(dirSync('./one', './two'));
});
I'd always be very suspicious of "plugins" who break the gulp-way in the very first line. If you don't need files in gulp-src
, you probably don't need gulp for that task, or there's something else fishy about it.
Gulp is already pretty good in copying files to someplace else, including exceptions, so why not use this built-in functionality? With the gulp-newer
plugin we can make sure that we just copy those files that have been updated:
var gulp = require('gulp');
var newer = require('gulp-newer');
var merge = require('merge2');
gulp.task('sync', function(done) {
return merge(
gulp.src(['./one/**/*', '!./one/**/__*'])
.pipe(newer('./two'))
.pipe(gulp.dest('./two')),
gulp.src(['./two/**/*', '!./two/**/__*'])
.pipe(newer('./one'))
.pipe(gulp.dest('./one'))
);
});
Here's the same code with some annotations:
var gulp = require('gulp');
var newer = require('gulp-newer');
var merge = require('merge2');
gulp.task('sync', function(done) {
return merge(
// Master directory one, we take all files except those
// starting with two underscores
gulp.src(['./one/**/*', '!./one/**/__*'])
// check if those files are newer than the same named
// files in the destination directory
.pipe(newer('./two'))
// and if so, copy them
.pipe(gulp.dest('./two')),
// Slave directory, same procedure here
gulp.src(['./two/**/*', '!./two/**/__*'])
.pipe(newer('./one'))
.pipe(gulp.dest('./one'))
);
});
That might also do the trick, no plugins required ;-)
Update
Assuming that you just want to copy from one
to two
, and that you might have a watcher running, you can use the "deleted" event from gulp to check which file has gone:
var gulp = require('gulp');
var newer = require('gulp-newer');
var path = require('path');
var del = require('del');
gulp.task('sync', function(done) {
return gulp.src(['./one/**/*', '!./one/**/__*'])
.pipe(newer('./two'))
.pipe(gulp.dest('./two'));
});
gulp.task('default', function() {
var watcher = gulp.watch('./one/**/*', ['sync']);
watcher.on('change', function(ev) {
if(ev.type === 'deleted') {
// path.relative gives us a string where we can easily switch
// directories
del(path.relative('./', ev.path).replace('one','two'));
}
});
});