tunnckoCore / blankr

:heart: tasks, todos, ideas, streaks, WIP, etc
https://i.am.charlike.online
4 stars 1 forks source link

micromatch wip (very old, first try) #30

Open tunnckoCore opened 9 years ago

tunnckoCore commented 9 years ago
var braces = require('braces')
var endsWith = require('ends-with')
var startsWith = require('starts-with')
var chars = require('regexp-special-chars')
var unixify = require('unixify')

module.exports = micromatch
micromatch.match = match;

function micromatch(str, pattern) {
  if (endsWith(pattern, '**') || endsWith(pattern, '**/')) {
    return [];
  }

  needle = braces(pattern)

  if (str[0] === '!') {
    needle = needle.map(function(item) {
      return esc(item.slice(1));
    });
  } else {
    needle = needle.map(function(item) {
      return esc(item);
    });
  }

  needle = '(?:' + needle.join('|') + ')';
  needle = needle.replace(/\\\?/g, '.{1}')
  needle = needle.replace(/\\\/\\\*\\\*/g, '/(?:.+?)');
  needle = needle.replace(/\\\*/g, '(?:.+?)');

  if (str[0] === '!') {
    needle = '(?!^' + needle + ')';
    var matches = str.match(needle);
    return matches.index === 0 ? true : false;
  }

  needle = new RegExp('^' + needle + '$');
  return needle.test(str)
}

function esc(str) {
  return str.replace(chars, '\\$&');
}

/**
 * Pass an array of files and a glob pattern as a string.
 * This function is called by the main `micromatch` function
 * If you only need to pass a single pattern you might get
 * minor speed improvements using this function.
 *
 * @param  {Array} `files`
 * @param  {Array} `pattern`
 * @param  {Object} `options`
 * @return {Array}
 */
function match(files, pattern, options) {
  if (typeof files !== 'string' && !Array.isArray(files)) {
    throw new Error('micromatch.match() expects a string or array.');
  }

  files = arrayify(files);
  var len = files.length;
  var res = [];
  var i = 0;

  while (i < len) {
    var fp = unixify(files[i++]);
    if (micromatch(fp, pattern)) {
      res.push(fp);
    }
  }
  return res;
}

/**
 * Coerce `val` to an array
 *
 * @param  {*} val
 * @return {Array}
 */
function arrayify(val) {
  return !Array.isArray(val)
    ? [val]
    : val;
}