twolfson / grunt-zip

Zip and unzip files via a grunt plugin
MIT License
87 stars 19 forks source link

Access zip archive name from router #40

Closed timtribers closed 8 years ago

timtribers commented 8 years ago

Hi @twolfson,

Great grunt task - am finding it very useful.

I particularly want to scan any number of zips and pull out a single file from each, if its there. I can get a task to pick up all the zips with a wildcard in the src. I can use the router to parse the file names and just extract the one I want. But, with one dest, and the file name being the same in each zip, of course, they overwrite each other.

Is there any way to access the zip archive name in the router, so that I can rename the file to follow its parent?

twolfson commented 8 years ago

We don't offer access to the src filename but it seems like you already have a finite list of files. As a result, you can restructure your code to programmatically define the configuration based on those names. For example:

// Define our config to build
var unzipConfig = {};

// Define our extraction targets
var zipToFilepathMap = {
  'a.zip': 'x/y/z',
  'b.zip': 'u/v/w'
};
Object.keys(zipToFileMap).forEach(function handleZips (zipFilename) {
  // Define a config for our filename
  var targetFilepath = zipToFileMap[zipFilename];
  unzipConfig[zipFilename] = {
    src: zipFilename,
    dest: 'dest/folder',
    router: function router (filepath) {
      // Skip over any files that aren't our target
      return filepath === targetFilepath ? filepath : null;
    }
  };
});

// Set config for unzip in Grunt
grunt.config.set('unzip', unzipConfig);

References:

timtribers commented 8 years ago

Hi @twolfson ,

Many thanks for taking the trouble to post that code. I had guessed that I would need to dynamically build the config, but your example will be a great help.