oleksii.sapov-erlinger
oleksii.sapov-erlinger

Reputation: 412

GULP: rename the affected file only

I want to create a copy with a new extension in the same folder only of the file which was changed. How should src and dest be specified?

var gulp = require('gulp'),
rename = require("gulp-rename"),
watch = require('gulp-watch');


var filePath = "./repo/**/*.xml"

gulp.task('watch', function () {    
    watch(filePath, gulp.series('rename'));
});


gulp.task('rename', function () {
    return gulp.src(???).pipe(rename(function (path) {
        path.extname = ".mei";
    })).pipe(gulp.dest(???));
});

Upvotes: 0

Views: 333

Answers (1)

Mark
Mark

Reputation: 182651

Try this:

var gulp = require('gulp'),
  rename = require("gulp-rename"),
  watch = require('gulp-watch'),
  changedInPlace = require('gulp-changed-in-place');


var filePath = "./repo/**/*.xml"

gulp.task('watch', function () {    
    watch(filePath, gulp.series('rename'));
});


gulp.task('rename', function () {
  return gulp.src(filePath)
    .pipe(changedInPlace())
    .pipe(rename(function (path) {
      console.log(path);
        path.extname = ".mei";
    }))
    .pipe(gulp.dest('repo'));
});

gulp.task('default', gulp.series('rename', 'watch'));

This uses the gulp-changed-in-place plugin to only pass through files that have changed in the same directory (in your case filePath).

It does have a firstRun option but I couldn't get it to work properly - maybe that option doesn't play well with gulp v4? To work around that, rename is called once before the watch is set up, see

gulp.task('default', gulp.series('rename', 'watch'));

Now it will only change the extension of the changed file and add that changed file back into the same directory it started in.

Upvotes: 0

Related Questions