UNPKG

1.87 kBJavaScriptView Raw
1'use strict';
2
3const picomatch = require('picomatch');
4const flatten = require('lodash/flatten');
5
6const NUMBER_REGEX = /^\d+$/;
7const RANGE_REGEX = /^(?<startGroup>\d+)-(?<endGroup>\d+)$/;
8const LINE_NUMBERS_REGEX = /^(?:\d+(?:-\d+)?,?)+$/;
9const DELIMITER = ':';
10
11const distinctArray = array => [...new Set(array)];
12const sortNumbersAscending = array => {
13 const sorted = [...array];
14 sorted.sort((a, b) => a - b);
15 return sorted;
16};
17
18const parseNumber = string => Number.parseInt(string, 10);
19const removeAllWhitespace = string => string.replace(/\s/g, '');
20const range = (start, end) => new Array(end - start + 1).fill(start).map((element, index) => element + index);
21
22const parseLineNumbers = suffix => sortNumbersAscending(distinctArray(flatten(
23 suffix.split(',').map(part => {
24 if (NUMBER_REGEX.test(part)) {
25 return parseNumber(part);
26 }
27
28 const {groups: {startGroup, endGroup}} = RANGE_REGEX.exec(part);
29 const start = parseNumber(startGroup);
30 const end = parseNumber(endGroup);
31
32 if (start > end) {
33 return range(end, start);
34 }
35
36 return range(start, end);
37 })
38)));
39
40function splitPatternAndLineNumbers(pattern) {
41 const parts = pattern.split(DELIMITER);
42 if (parts.length === 1) {
43 return {pattern, lineNumbers: null};
44 }
45
46 const suffix = removeAllWhitespace(parts.pop());
47 if (!LINE_NUMBERS_REGEX.test(suffix)) {
48 return {pattern, lineNumbers: null};
49 }
50
51 return {pattern: parts.join(DELIMITER), lineNumbers: parseLineNumbers(suffix)};
52}
53
54exports.splitPatternAndLineNumbers = splitPatternAndLineNumbers;
55
56function getApplicableLineNumbers(normalizedFilePath, filter) {
57 return sortNumbersAscending(distinctArray(flatten(
58 filter
59 .filter(({pattern, lineNumbers}) => lineNumbers && picomatch.isMatch(normalizedFilePath, pattern))
60 .map(({lineNumbers}) => lineNumbers)
61 )));
62}
63
64exports.getApplicableLineNumbers = getApplicableLineNumbers;