Skip to content

Commit a6d15ea

Browse files
author
Stas Germanovskiy
committed
BUG-505 fix #505
1 parent 29bd767 commit a6d15ea

File tree

2 files changed

+34
-5
lines changed

2 files changed

+34
-5
lines changed

src/formatter/formatCommaPositions.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ export default function formatCommaPositions(
3232
* [
3333
* 'SELECT',
3434
* ' foo,',
35-
* ' bar,',
35+
* ' bar, --comment',
3636
* ' baz',
3737
* 'FROM'
3838
* ]
@@ -41,7 +41,7 @@ export default function formatCommaPositions(
4141
*
4242
* [
4343
* ['SELECT'],
44-
* [' foo,', ' bar,', ' baz'],
44+
* [' foo,', ' bar, --comment', ' baz'],
4545
* ['FROM']
4646
* ]
4747
*/
@@ -52,7 +52,7 @@ function groupCommaDelimitedLines(lines: string[]): string[][] {
5252
// when line ends with comma,
5353
// gather together all following lines that also end with comma,
5454
// plus one (which doesn't end with comma)
55-
while (lines[i].match(/.*,$/)) {
55+
while (lines[i].match(/.*,((\s*--.+)|$)/)) {
5656
i++;
5757
group.push(lines[i]);
5858
}
@@ -68,7 +68,11 @@ function formatTabular(commaLines: string[]): string[] {
6868
if (i === commaLines.length - 1) {
6969
return line; // do not add comma for last item
7070
}
71-
return line + ' '.repeat(maxLineLength - line.length - 1) + ',';
71+
const commentMatch = /\s*--/.exec(line);
72+
const endOfLinePosition = commentMatch ? commentMatch.index : line.length;
73+
return `${line.slice(0, endOfLinePosition)}${' '.repeat(
74+
maxLineLength - line.length - 1
75+
)},${line.slice(endOfLinePosition + 1)}`;
7276
});
7377
}
7478

@@ -91,5 +95,5 @@ function removeLastIndent(whitespace: string, indent: string): string {
9195
}
9296

9397
function trimTrailingCommas(lines: string[]): string[] {
94-
return lines.map(line => line.replace(/,$/, ''));
98+
return lines.map(line => line.replace(/,((\s*--.+)|$)/, '$1'));
9599
}

test/options/commaPosition.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,31 @@ export default function supportsCommaPosition(format: FormatFn) {
4848
);
4949
});
5050

51+
it('adds comma before column in case with comment', () => {
52+
const result = format(
53+
`SELECT alpha,
54+
MAX(beta), --comment
55+
delta AS d, epsilon FROM gamma GROUP BY alpha, delta, epsilon
56+
`,
57+
{ commaPosition: 'before' }
58+
);
59+
expect(result).toBe(
60+
dedent(`
61+
SELECT
62+
alpha
63+
, MAX(beta) --comment
64+
, delta AS d
65+
, epsilon
66+
FROM
67+
gamma
68+
GROUP BY
69+
alpha
70+
, delta
71+
, epsilon
72+
`)
73+
);
74+
});
75+
5176
it('works with larger indent', () => {
5277
const result = format(
5378
'SELECT alpha, MAX(beta), delta AS d, epsilon FROM gamma GROUP BY alpha, delta, epsilon',

0 commit comments

Comments
 (0)