aboutsummaryrefslogtreecommitdiff
path: root/node_modules/glob2base/index.js
blob: 307e3f27cc828b06d5ed48d99b2df9830523adc4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
'use strict';

var path = require('path');
var findIndex = require('find-index');

var flattenGlob = function(arr){
  var out = [];
  var flat = true;
  for(var i = 0; i < arr.length; i++) {
    if (typeof arr[i] !== 'string') {
      flat = false;
      break;
    }
    out.push(arr[i]);
  }

  // last one is a file or specific dir
  // so we pop it off
  if (flat) {
    out.pop();
  }
  return out;
};

var flattenExpansion = function(set) {
  var first = set[0];
  var toCompare = set.slice(1);

  // find index where the diff is
  var idx = findIndex(first, function(v, idx){
    if (typeof v !== 'string') {
      return true;
    }

    var matched = toCompare.every(function(arr){
      return v === arr[idx];
    });

    return !matched;
  });

  return first.slice(0, idx);
};

var setToBase = function(set) {
  // normal something/*.js
  if (set.length <= 1) {
    return flattenGlob(set[0]);
  }
  // has expansion
  return flattenExpansion(set);
};

module.exports = function(glob) {
  var set = glob.minimatch.set;
  var baseParts = setToBase(set);
  var basePath = path.normalize(baseParts.join(path.sep))+path.sep;
  return basePath;
};