UNPKG

2.18 kBJavaScriptView Raw
1'use strict';
2
3var startsWith = require('path-starts-with');
4var normalizePath = require('normalize-path');
5
6function containsPath(filepath, substr, options) {
7 if (typeof filepath !== 'string') {
8 throw new TypeError('expected filepath to be a string');
9 }
10 if (typeof substr !== 'string') {
11 throw new TypeError('expected substring to be a string');
12 }
13
14 if (substr === '') {
15 return false;
16 }
17
18 // return true if the given strings are an exact match
19 if (filepath === substr) {
20 return true;
21 }
22
23 if (substr.charAt(0) === '!') {
24 return !containsPath(filepath, substr.slice(1), options);
25 }
26
27 options = options || {};
28 if (options.nocase === true) {
29 filepath = filepath.toLowerCase();
30 substr = substr.toLowerCase();
31 }
32
33 var fp = normalize(filepath, false);
34 var str = normalize(substr, false);
35
36 // return false if the normalized substring is only a slash
37 if (str === '/') {
38 return false;
39 }
40
41 // if normalized strings are equal, return true
42 if (fp === str) {
43 return true;
44 }
45
46 if (startsWith(filepath, substr, options)) {
47 return true;
48 }
49
50 var idx = fp.indexOf(str);
51 var prefix = substr.slice(0, 2);
52
53 // if the original substring started with "./", we'll
54 // assume it should match from the beginning of the string
55 if (prefix === './' || prefix === '.\\') {
56 return idx === 0;
57 }
58
59 if (idx !== -1) {
60 if (options.partialMatch === true) {
61 return true;
62 }
63
64 // if the first character in the substring is a
65 // dot or slash, we can consider this a match
66 var ch = str.charAt(0);
67 if (ch === '/') {
68 return true;
69 }
70
71 // since partial matches were not enabled, we only consider
72 // this a match if the next character is a dot or a slash
73 var before = fp.charAt(idx - 1);
74 var after = fp.charAt(idx + str.length);
75 return (before === '' || before === '/')
76 && (after === '' || after === '/');
77 }
78
79 return false;
80}
81
82/**
83 * Normalize paths
84 */
85
86function normalize(str) {
87 str = normalizePath(str, false);
88 if (str.slice(0, 2) === './') {
89 str = str.slice(2);
90 }
91 return str;
92}
93
94/**
95 * Expose `containsPath`
96 */
97
98module.exports = containsPath;