minimatch | mini parser | Cell 3 | Search

This code provides a minimatch function that allows you to match filenames against simplified glob-like patterns by converting them into regular expressions. It handles brace expansions, splits patterns into segments, parses them into regexps, and efficiently tests filename matches against the resulting expression.

Run example

npm run import -- "minimatch"

minimatch

var importer = require('../Core')
var expand = importer.import("expand")
var parse = importer.import("mini parser")

function regExpEscape (s) {
  return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\${OUTPUT}amp;')
}

// convert minimatch expression to regular expression
function minimatch (filename, pattern) {
    // expand braces
    var set = expand(pattern)

        // matching patterns.
        .map(function (s) {
            return s.split(/\/+/)
        })

        // glob --> regexps
        .map(function (s, si, set) {
            return s.map(parse)
        })

        // filter out everything that didn't compile properly.
        .filter(function (s) {
            return s.indexOf(false) === -1
        })

        // convert the sets to regular expressions
        .map(function (pattern) {
            return pattern.map(function (p) {
                return (typeof p.glob === 'boolean') 
                    ? '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
                    : (typeof p === 'string') ? regExpEscape(p)
                    : p._src
            }).join('\\\/')
        }).join('|')
    try {
        var re = new RegExp('^(?:' + set + ')


, 'i')
        return filename.match(re) !== null
    } catch (ex) {
        throw ex
    }
}

module.exports = {
    minimatch
}

What the code could have been:

const { importFunctions } = require('../Core');

const expand = importFunctions('expand');
const parse = importFunctions('mini parser');

/**
 * Escape special characters in a string to use in a regular expression.
 *
 * @param {string} s - The string to escape.
 * @returns {string} The escaped string.
 */
function regExpEscape(s) {
  return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\${OUTPUT}amp;');
}

/**
 * Convert a minimatch expression to a regular expression.
 *
 * @param {string} filename - The filename to match.
 * @param {string} pattern - The minimatch expression.
 * @returns {boolean} Whether the filename matches the pattern.
 */
function minimatch(filename, pattern) {
  try {
    // Expand braces in the minimatch expression.
    const expanded = expand(pattern);

    // Split the expanded pattern into individual paths.
    const paths = expanded.map((s) => s.split(/\//g));

    // Parse each path into a regular expression.
    const regexps = paths.map((path, index, paths) => {
      return path.map((segment, segmentIndex) => {
        const parsedSegment = parse(segment);
        if (parsedSegment === false) {
          // If the segment is invalid, return null.
          return null;
        }
        if (typeof parsedSegment.glob === 'boolean') {
          // If the segment is a glob, match any characters except directory separators.
          return '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
        } else if (typeof parsedSegment ==='string') {
          // If the segment is a string, escape special characters.
          return regExpEscape(parsedSegment);
        } else {
          // If the segment is a parsed segment, use its source.
          return parsedSegment._src;
        }
      });
    });

    // Filter out any paths that were invalid.
    const validPaths = regexps.filter((path) => path.every((segment) => segment!== null));

    // Convert each valid path to a regular expression.
    const compiled = validPaths.map((path) => {
      return path.join('\\/');
    });

    // Join the compiled paths with '|' and wrap in a regular expression.
    const re = new RegExp('^' + compiled.join('|') + '


, 'i');

    // Return whether the filename matches the regular expression.
    return filename.match(re)!== null;
  } catch (error) {
    // If an error occurs, throw it.
    throw error;
  }
}

module.exports = {
  minimatch,
};

This code implements a minimatch function that performs pattern matching on filenames using a simplified glob-like syntax.

Here's a breakdown:

  1. Imports:

  2. regExpEscape Function:

  3. minimatch Function:

  4. Exports: