Skip to content

Commit

Permalink
Fix: Handle multiline comments in parseWithComments
Browse files Browse the repository at this point in the history
This problem was found while using prettier with pragmas enabled and I
backtracked it to the `parseWithComments` function from jest-docblock.
In this context it is especially problematic in cases were the top level
comment is not formatted as a dock lock but a "multi-line comment" to
disable an es-lint rule.

/* eslint-disable @typescript-eslint/unbound-method */

Especially given the fact that the `extract` function seems to handle
this case correctly.

Therefore this solution alters the commentStartRe to keep the second * as
optional. This should ensure that all existing use cases work as expected
with proper docblocks but also ensures that an "invalid" multiline comment
works as well.

Links:
https://github.com/ullumullu/jest/blob/main/packages/jest-docblock/src/__tests__/index.test.ts#L29
  • Loading branch information
ssterb committed May 13, 2022
1 parent 379f6de commit 2c65c33
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
21 changes: 21 additions & 0 deletions packages/jest-docblock/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ describe('docblock', () => {
expect(docblock.extract(code)).toBe(`/*${EOL} * @team foo${EOL}*/`);
});

it('extracts from invalid docblock singleline', () => {
const code = `/* some comment @team foo */${EOL}const x = foo;`;
expect(docblock.extract(code)).toBe('/* some comment @team foo */');
});

it('returns extract and parsedocblock', () => {
const code = `/** @provides module-name */${EOL}${EOL}.dummy {}${EOL}`;

Expand Down Expand Up @@ -204,6 +209,22 @@ describe('docblock', () => {
});
});

it('extract from invalid docblock', () => {
const code = `/* @format: everything${EOL}// keep me */`;
expect(docblock.parseWithComments(code)).toEqual({
comments: '// keep me',
pragmas: {'format:': 'everything'},
});
});

it('extract from invalid docblock singleline', () => {
const code = '/* some test */';
expect(docblock.parseWithComments(code)).toEqual({
comments: ' some test',
pragmas: {},
});
});

it('extracts docblock comments as CRLF when docblock contains CRLF', () => {
const code = '/**\r\n * foo\r\n * bar\r\n*/';
expect(docblock.parseWithComments(code)).toEqual({
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-docblock/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import detectNewline = require('detect-newline');
type Pragmas = Record<string, string | Array<string>>;

const commentEndRe = /\*\/$/;
const commentStartRe = /^\/\*\*/;
const commentStartRe = /^\/\*\*?/;
const docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/;
const lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g;
const ltrimNewlineRe = /^(\r?\n)+/;
Expand Down

0 comments on commit 2c65c33

Please sign in to comment.