Skip to content

Instantly share code, notes, and snippets.

@evensandbox
Created May 6, 2014 13:55
Show Gist options
  • Select an option

  • Save evensandbox/9c0bcbc981db537c8292 to your computer and use it in GitHub Desktop.

Select an option

Save evensandbox/9c0bcbc981db537c8292 to your computer and use it in GitHub Desktop.
grunt-contrib-delete.js
grunt.registerMultiTask('delete', function(when, task) {
var path = require( 'path' ), fs = require( 'fs' );
var queue = function( list, fn, callback, index, ret ) {
"use strict";
index = index || 0;
ret = ret || [];
var next = function ( value, stop, returnCurrentValue ) {
ret[ ret.length ] = value;
if ( stop ) {
return callback.apply( null, returnCurrentValue ? [value] : ret );
}
queue( list, fn, callback, ++index, ret );
};
if ( index < list.length ) {
var argus = [ list[ index ], index, ret ];
if ( fn.length ) {
argus = argus.slice( 0, fn.length - 1 );
}
argus.push( next );
fn.apply( null, argus );
}
else if ( callback ) {
callback.apply( null, ret );
}
};
function rmdir( file, cb ) {
if ( grunt.file.isDir(file) ) {
queue( fs.readdirSync(file), function( f, next ) {
rmdir( path.resolve(file, f), next );
}, function() {
fs.rmdirSync( file );
cb();
});
}
else {
fs.unlinkSync( file );
cb();
}
}
this.filesSrc.forEach(function( file ) {
rmdir( path.resolve( __dirname, file ), function() {} );
});
});
grunt.registerTask( 'default', [ 'delete' ] );
@evensandbox
Copy link
Author

  grunt.registerMultiTask('delete', function(when, task) {
    var path = require( 'path' ), fs = require( 'fs' );
    this.files.forEach(function( fileObj ) {
      var files = grunt.file.expand({nonull: true}, fileObj.src);
      var i = 2;
      while ( i-- > 0 ) {
        files.forEach(function( file ) {
          if ( grunt.file.isPathCwd(file) || !grunt.file.isPathInCwd(file) ) return;
          file = path.resolve( file );
          if ( grunt.file.exists( file ) ) {
            if ( grunt.file.isDir(file) ) {
              if ( fs.readdirSync(file).length == 0 ) {
                fs.rmdirSync(file);
              }
            }
            else {
              grunt.file.delete( file );
            }
          }        
        });      
      }
    });

  });

  grunt.registerTask( 'default', [ 'delete' ] );

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