gruntjsgrunt-contrib-watchgrunt-shell

Pass the name of watched file that changed as argument to a shell command


I have a collection of .svg files. When I modify one of them, I would like grunt to re-run a command on each svg file that was modified

inkscape --file=FILENAME.svg --export-pdf=FILENAME.pdf

So far, I have this grunt script

module.exports = function (grunt) {
'use strict';
grunt.initConfig({
  shell: {
    figures: {
      command: 'inkscape --file=FILENAME.svg --export-pdf=FILENAME.pdf'
    }
  },
  watch: {
    figs: {
      files: '**/*.svg',
      tasks: ['shell:figures']
    }
  }
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-shell');

grunt.registerTask('default', [watch']);
};

But I have no idea how to configure grunt in order to replace FILENAME by the name of each file that was modified.


Solution

  • I solved the issue using a config variable that is modified on the watch event before shell:figs runs

    module.exports = function (grunt) {
      'use strict';
      // Project configuration
      grunt.initConfig({
        shell: {
          figs: {
            command: function() {
              return 'inkscape --file="' + grunt.config('shell.figs.src') + '" --export-pdf="' + grunt.config('shell.figs.src').replace('.svg', '.pdf') + '"';
            },
            src: '**/*.svg'
          }
        },
        watch: {
          svgs: {
            files: '**/*.svg',
            tasks: ['shell:figs'],
            options: {
            spawn: false,
            }
          }
        }
      });
    
      grunt.event.on('watch', function(action, filepath) {
        grunt.config('shell.figs.src', filepath);
      });
    
      // These plugins provide necessary tasks
      grunt.loadNpmTasks('grunt-contrib-watch');
      grunt.loadNpmTasks('grunt-shell');
    
      // Default task
      grunt.registerTask('default', ['connect', 'watch']);
    };
    

    The only downside is that shell:figs cannot be called manually, it only works when running the watch task, or simply grunt.