blob: c3ca766a7bef961c6cc9c5b5e04c930aa05d7608 [file] [log] [blame]
Yang Guo4fd355c2019-09-19 10:59:03 +02001'use strict';
2
3const path = require('path');
4const win32 = process.platform === 'win32';
5const {
Tim van der Lippe459f4022021-02-19 12:09:57 +00006 REGEX_BACKSLASH,
7 REGEX_REMOVE_BACKSLASH,
Yang Guo4fd355c2019-09-19 10:59:03 +02008 REGEX_SPECIAL_CHARS,
Tim van der Lippe459f4022021-02-19 12:09:57 +00009 REGEX_SPECIAL_CHARS_GLOBAL
Yang Guo4fd355c2019-09-19 10:59:03 +020010} = require('./constants');
11
12exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
13exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
14exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
15exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
Tim van der Lippe459f4022021-02-19 12:09:57 +000016exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
Yang Guo4fd355c2019-09-19 10:59:03 +020017
18exports.removeBackslashes = str => {
19 return str.replace(REGEX_REMOVE_BACKSLASH, match => {
20 return match === '\\' ? '' : match;
21 });
Tim van der Lippe459f4022021-02-19 12:09:57 +000022};
Yang Guo4fd355c2019-09-19 10:59:03 +020023
24exports.supportsLookbehinds = () => {
Tim van der Lippe459f4022021-02-19 12:09:57 +000025 const segs = process.version.slice(1).split('.').map(Number);
26 if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
Yang Guo4fd355c2019-09-19 10:59:03 +020027 return true;
28 }
29 return false;
30};
31
32exports.isWindows = options => {
33 if (options && typeof options.windows === 'boolean') {
34 return options.windows;
35 }
36 return win32 === true || path.sep === '\\';
37};
38
39exports.escapeLast = (input, char, lastIdx) => {
Tim van der Lippe459f4022021-02-19 12:09:57 +000040 const idx = input.lastIndexOf(char, lastIdx);
Yang Guo4fd355c2019-09-19 10:59:03 +020041 if (idx === -1) return input;
42 if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
Tim van der Lippe459f4022021-02-19 12:09:57 +000043 return `${input.slice(0, idx)}\\${input.slice(idx)}`;
44};
45
46exports.removePrefix = (input, state = {}) => {
47 let output = input;
48 if (output.startsWith('./')) {
49 output = output.slice(2);
50 state.prefix = './';
51 }
52 return output;
53};
54
55exports.wrapOutput = (input, state = {}, options = {}) => {
56 const prepend = options.contains ? '' : '^';
57 const append = options.contains ? '' : '$';
58
59 let output = `${prepend}(?:${input})${append}`;
60 if (state.negated === true) {
61 output = `(?:^(?!${output}).*$)`;
62 }
63 return output;
Yang Guo4fd355c2019-09-19 10:59:03 +020064};