Skip to content

Commit f98eecf

Browse files
committed
Improve how we handle RegExps in TypeScript
1 parent 2d6dd49 commit f98eecf

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

src/git.ts

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -84,28 +84,36 @@ const isHunkHeader = (input: string) => {
8484
};
8585

8686
const getRangeForChangedLines = (line: string) => {
87+
/**
88+
* Example values of the RegExp's group:
89+
*
90+
* start: '7',
91+
* linesCountDelimiter: ',2',
92+
* linesCount: '2',
93+
*/
8794
const rangeRE = new RegExp(
8895
/^@@ .* \+(?<start>\d+)(?<linesCountDelimiter>,(?<linesCount>\d+))? @@/
8996
);
9097
const range = rangeRE.exec(line);
9198
if (range === null) {
9299
throw Error(`Couldn't match regex with line '${line}'`);
93100
}
94-
if (range.groups?.start === undefined) {
95-
/*
96-
* NOTE: Never happens, because RegExp requires start to be a
97-
* required number
98-
*/
99-
throw Error("Couldn't match regex to find start");
100-
}
101+
102+
const groups = {
103+
// Fallback value to ensure hasAddedLines resolves to false
104+
start: "0",
105+
linesCountDelimiter: ",0",
106+
linesCount: "0",
107+
...range.groups,
108+
};
101109

102110
const linesCount: number =
103-
range.groups.linesCountDelimiter && range.groups.linesCount
104-
? parseInt(range.groups.linesCount)
111+
groups.linesCountDelimiter && groups.linesCount
112+
? parseInt(groups.linesCount)
105113
: 1;
106114

107115
const hasAddedLines = linesCount !== 0;
108-
const start: number = parseInt(range.groups.start);
116+
const start: number = parseInt(groups.start);
109117
const end = start + linesCount;
110118

111119
return hasAddedLines ? new Range(start, end) : null;

0 commit comments

Comments
 (0)