Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a custom grunt task for processing files

I am trying to write a grunt task that would go over a set of input files and run a transformation on each file. let's assume the input files are given by *.in and for each of them the task will create an .out file.

From what I read, it seems that the config should look something like this

grunt.initConfig({
    my_task: {
        src: 'C:/temp/*.in',
        dest: 'C:/temp/output/*.out'
    }
});

and the task registration should be:

grunt.registerTask('my_task', 'iterate files', function() {
    //iterate files.
});

I cannot figure out how to make grunt send me the list of files and iterate over them.

Any idea how to do it?

like image 825
elewinso Avatar asked Sep 16 '13 08:09

elewinso


1 Answers

This is what I ended doing and what solved my problem. for the task configuration I did the following:

  grunt.initConfig({
    convert_po: {
      build: {
        src: 'C:/temp/Locale/*.po',
        dest: 'C:/temp/Locale/output/'
      }
    }
  });

and this is the task's implementation:

  grunt.registerMultiTask('convert_po', 'Convert PO files to JSON format', function() {
var po = require('node-po');
var path = require('path');

grunt.log.write('Loaded dependencies...').ok();

//make grunt know this task is async.
var done = this.async();

var i =0;
this.files.forEach(function(file) {
  grunt.log.writeln('Processing ' + file.src.length + ' files.');

  //file.src is the list of all matching file names.
  file.src.forEach(function(f){ 
    //this is an async function that loads a PO file
    po.load(f, function(_po){
      strings = {};
        for (var idx in _po.items){
            var item = _po.items[idx];
            strings[item.msgid] = item.msgstr.length == 1 ? item.msgstr[0] : item.msgstr;
        }
        var destFile = file.dest + path.basename(f, '.po') + '.json';
        grunt.log.writeln('Now saving file:' + destFile);
        fs.writeFileSync(destFile, JSON.stringify(strings, null, 4));

        //if we processed all files notify grunt that we are done.
        if( i >= file.src.length) done(true);
    });
  });
});
});
like image 102
elewinso Avatar answered Oct 14 '22 22:10

elewinso