1 | 'use strict';
|
2 |
|
3 | const picomatch = require('picomatch');
|
4 | const flatten = require('lodash/flatten');
|
5 |
|
6 | const NUMBER_REGEX = /^\d+$/;
|
7 | const RANGE_REGEX = /^(?<startGroup>\d+)-(?<endGroup>\d+)$/;
|
8 | const LINE_NUMBERS_REGEX = /^(?:\d+(?:-\d+)?,?)+$/;
|
9 | const DELIMITER = ':';
|
10 |
|
11 | const distinctArray = array => [...new Set(array)];
|
12 | const sortNumbersAscending = array => {
|
13 | const sorted = [...array];
|
14 | sorted.sort((a, b) => a - b);
|
15 | return sorted;
|
16 | };
|
17 |
|
18 | const parseNumber = string => Number.parseInt(string, 10);
|
19 | const removeAllWhitespace = string => string.replace(/\s/g, '');
|
20 | const range = (start, end) => new Array(end - start + 1).fill(start).map((element, index) => element + index);
|
21 |
|
22 | const 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 |
|
40 | function 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 |
|
54 | exports.splitPatternAndLineNumbers = splitPatternAndLineNumbers;
|
55 |
|
56 | function 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 |
|
64 | exports.getApplicableLineNumbers = getApplicableLineNumbers;
|