Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner 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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.