Skip to content

Instantly share code, notes, and snippets.

@ctalkington
Created September 12, 2012 02:44
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ctalkington/3703920 to your computer and use it in GitHub Desktop.
Save ctalkington/3703920 to your computer and use it in GitHub Desktop.
Grunt Glob to Multi Files Object
// gruntfile dropin used to build a grunt files object with 1:1 structure
function globToMultiFiles(glob, dest, options) {
var path = require('path');
grunt.util = grunt.util || grunt.utils;
dest = grunt.template.process(dest);
options = grunt.util._.defaults(options || {}, {
cwd: '',
minimatch: {},
processName: false
});
if (options.cwd.length > 0) {
options.minimatch.cwd = options.cwd;
}
var result = {};
var destFile;
var srcFile;
var fileName;
var filePath;
grunt.file.expandFiles(options.minimatch, glob).forEach(function(file) {
fileName = path.basename(file);
filePath = path.dirname(file);
srcFile = path.join(options.cwd, file);
if (options.processName && grunt.util.kindOf(options.processName) === 'function') {
fileName = options.processName(fileName) || fileName;
}
destFile = path.join(dest, filePath, fileName);
result[destFile] = srcFile;
});
return result;
}
...
// files in src to dest/src
globToMultiFiles('src/*', 'dest');
// files and folders in src to dest (retaining structure)
globToMultiFiles('**', 'dest', {cwd: 'src'});
// files and folders in src to dest (retaining structure)
// replace ext, example use case stylus
globToMultiFiles('**', 'dest', {
cwd: 'src',
processName: function(fileName) {
fileName = fileName.replace('.styl', '.css');
return fileName;
}
});
...
task: {
target: {
files: globToMultiFiles(...)
}
}
@ctalkington
Copy link
Author

this works pretty well for single level dirs, i need to revamp it a bit to properly handle multiple levels.

@ctalkington
Copy link
Author

updated to support cwd and deep paths.

@ctalkington
Copy link
Author

@tkellen updated this a bit. let me know what you think. should be more versatile.

@ctalkington
Copy link
Author

dest is now processed as a template.

@jbcurtin
Copy link

I'm not that great at node, can you provide a working example to implement this with the commandline? My command currently looks like:
$ NODE_PATH=path/to/dir/with/grunt.js jade in_dir -o out_dir

@rikkertkoppes
Copy link

Note that expandFiles has been removed from grunt, adjust as follows:

....
options.minimatch.filter = 'isFile';
....
grunt.file.expand(options.minimatch, glob).forEach(function(file) {
....

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