Skip to content

Commit 21b4b53

Browse files
committed
refactor: generalize line handling and fix edge cases
- Refactor getPositionIndicator to handle any line number dynamically - Normalize \r\n and \r to \n for cross-platform compatibility - Simplify code by using split approach instead of hard-coded line handling - Works for header, body, footer, and any future line numbers
1 parent 72afc3e commit 21b4b53

1 file changed

Lines changed: 18 additions & 41 deletions

File tree

@commitlint/format/src/format.ts

Lines changed: 18 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -83,49 +83,26 @@ function getPositionIndicator(
8383
const padding = " ";
8484

8585
const tilde = "~";
86-
let indicator = "";
87-
88-
if (start.line === 1) {
89-
const spacesBefore = Math.max(0, start.column - 1);
90-
const tildeLength = Math.max(1, end.column - start.column);
91-
indicator = padding + " ".repeat(spacesBefore) + tilde.repeat(tildeLength);
92-
} else if (start.line === 2) {
93-
const headerEndIndex = input.indexOf("\n\n");
94-
if (headerEndIndex === -1) return undefined;
95-
96-
const bodyText = input.slice(headerEndIndex + 2);
97-
const firstBodyLine = bodyText.split("\n")[0];
98-
const lineLength = firstBodyLine.length;
99-
100-
if (start.column <= lineLength + 1) {
101-
const spacesBefore = Math.max(0, start.column - 1);
102-
const tildeLength = Math.max(
103-
1,
104-
Math.min(end.column - start.column, lineLength - (start.column - 1)),
105-
);
106-
indicator =
107-
padding + " ".repeat(spacesBefore) + tilde.repeat(tildeLength);
108-
}
109-
} else if (start.line === 3) {
110-
const footerStartIndex = input.lastIndexOf("\n\n");
111-
if (footerStartIndex === -1) return undefined;
112-
113-
const footerText = input.slice(footerStartIndex + 2);
114-
const firstFooterLine = footerText.split("\n")[0];
115-
const lineLength = firstFooterLine.length;
116-
117-
if (start.column <= lineLength + 1) {
118-
const spacesBefore = Math.max(0, start.column - 1);
119-
const tildeLength = Math.max(
120-
1,
121-
Math.min(end.column - start.column, lineLength - (start.column - 1)),
122-
);
123-
indicator =
124-
padding + " ".repeat(spacesBefore) + tilde.repeat(tildeLength);
125-
}
86+
87+
const normalizedInput = input.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
88+
const lines = normalizedInput.split("\n");
89+
const targetLine = lines[start.line - 1];
90+
91+
if (!targetLine) {
92+
return undefined;
12693
}
12794

128-
return indicator || undefined;
95+
const lineLength = targetLine.length;
96+
const spacesBefore = Math.max(0, start.column - 1);
97+
const tildeLength = Math.max(
98+
1,
99+
Math.min(end.column - start.column, lineLength - (start.column - 1)),
100+
);
101+
102+
const indicator =
103+
padding + " ".repeat(spacesBefore) + tilde.repeat(tildeLength);
104+
105+
return indicator;
129106
}
130107

131108
export function formatResult(

0 commit comments

Comments
 (0)