Skip to content

Instantly share code, notes, and snippets.

@akaleeroy
Last active May 6, 2021 10:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akaleeroy/762c635d1ad340b78762e793df4139ef to your computer and use it in GitHub Desktop.
Save akaleeroy/762c635d1ad340b78762e793df4139ef to your computer and use it in GitHub Desktop.
Gulp replace only relevant files

gulp-replace only relevant files

gulp replace only relevant files demo

Piping to gulp.dest would re-write all input files. This checks for the pattern first and only passes along files that actually need to be processed, avoiding unnecessary overwriting with the same content. A benefit is that your files' timestamps stay meaningful.

const gulp = require('gulp');
const log = require('gulp/node_modules/fancy-log');
const replace = require('gulp-replace');
const only = require('gulp-ignore').include;
const path = require('path');
const SRC = 'data/*.csv';
const DEST = 'data/';
gulp.task('clean:diacritics', (done) => {
const REPLACEMENTS = {
'Ş': 'Ș',
'ş': 'ș',
'Ţ': 'Ț',
'ţ': 'ț',
'Ã': 'Ă',
'ã': 'ă',
};
const dirty = new RegExp(`[${Object.keys(REPLACEMENTS).join('')}]`, 'g');
gulp.src(SRC)
.pipe(only((file) => {
let result = dirty.test(String(file.contents));
file.basename = path.parse(file.history[0]).base;
if (result) log(`Cleaning '${file.basename}'`);
return result;
}))
.pipe(replace(dirty, (match) => REPLACEMENTS[match]))
.pipe(gulp.dest(DEST))
.on('end', () => {
log('Done. Wrong diacritics have been smitten!');
done();
});
});
gulp.task('clean', ['clean:diacritics']);
@akaleeroy
Copy link
Author

akaleeroy commented Mar 31, 2018

A more generic solution would be better
Maybe something like:

gulp.src(SRC)
.pipe(hash)
.pipe(replace(dirty, match => REPLACEMENTS[match]))
.pipe(onlyHashChanged)
.pipe(gulp.dest(DEST))

Or using gulp-snapshot

gulp.src(SRC)
.pipe(snapshot.take())
.pipe(replace(dirty, match => REPLACEMENTS[match]))
.pipe(snapshot.take())
.pipe(snapshot.compare( difference => {
  // OK now WTF?! How to NOT passthrough if difference.noChanges?!
}
.pipe(gulp.dest(DEST))

@NomanChali
Copy link

.pipe(snapshot.compare( difference => {
  // OK now WTF?! How to NOT passthrough if difference.noChanges?!
}

hi is there any way, how to passthrough only changed files to gulp dest.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment