Search code examples
gulp

Any way in Gulp to get matched glob pattern in stream?


Is there any way to know what glob pattern a Vinyl object in Gulp's src() stream matched? With for example the rename plugin, I can get the Vinyl object and get its path, dirname, and the like. But right now in my Gulpfile I have some logic to recreate the glob pattern via a lookup table (for syncing to a local live site from the dev repo).


Solution

  • I can't see any documentation suggesting that the matched glob pattern is recorded alongside the file. If you pass an array into gulp.src, you can try and match the path of the current file to the array using the micromatch library. This would require the glob patterns passed in to be unique in that no more than one pattern could match a particular file.

    An example to do this:

    const gulp = require('gulp'),
        tap = require('gulp-tap'),
        mm = require('micromatch');
    
    function example() {
        const srcGlobPatternsArray = ['src/js/**/*.js', 'src/css/**/*.css'];
        return gulp.src(srcGlobPatternsArray).pipe(
            tap((file) => {
                const globIndex = srcGlobPatternsArray.findIndex((element) => {
                    return mm.isMatch(
                        file.history[0].substring(file.cwd.length + 1),
                        element
                    );
                });
                if (globIndex !== -1) {
                    console.log(
                        'Glob pattern matched: ' +
                            srcGlobPatternsArray[globIndex] +
                            ' at index ' +
                            globIndex
                    );
                } else {
                    console.log('Could not match glob');
                }
            })
        );
    }
    
    exports.default = example;