Skip to content

Commit 64a8dca

Browse files
brettz9claude
andcommitted
fix(convert-to-jsdoc-comments): merge stacked line comments into a single JSDoc block
Previously the fixer only converted the last of several consecutive `//` comments preceding a node, leaving earlier lines behind and anchoring the report on the last line as if it were the sole offender. Now the rule walks back through directly adjacent `//` comments and merges them all into one JSDoc block, anchoring the report on the first line of the group. Fixes #1764 Co-Authored-By: Claude Sonnet 5 <[email protected]>
1 parent eade377 commit 64a8dca

3 files changed

Lines changed: 219 additions & 19 deletions

File tree

‎docs/rules/convert-to-jsdoc-comments.md‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,33 @@ var a = []; // Test comment
225225
const SENIORITY_ORDER = ['senior', 'middle', 'specialist'];
226226
// "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"contexts":["any"],"lineOrBlockStyle":"block"}]
227227
// Message: Block comments should be JSDoc-style.
228+
229+
// one
230+
// two
231+
// three
232+
type Foo = string;
233+
// "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"contexts":["TSTypeAliasDeclaration"]}]
234+
// Message: Line comments should be JSDoc-style.
235+
236+
// one
237+
// two
238+
// three
239+
function quux () {}
240+
// "jsdoc/convert-to-jsdoc-comments": ["error"|"warn", {"enforceJsdocLineStyle":"single"}]
241+
// Message: Line comments should be JSDoc-style.
242+
243+
// separate paragraph
244+
245+
// one
246+
// two
247+
function quux () {}
248+
// Message: Line comments should be JSDoc-style.
249+
250+
// eslint-disable-next-line no-magic-numbers
251+
// one
252+
// two
253+
function quux () {}
254+
// Message: Line comments should be JSDoc-style.
228255
````
229256

230257

‎src/rules/convertToJsdocComments.js‎

Lines changed: 90 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -163,8 +163,11 @@ export default {
163163
* @param {import('eslint').Rule.Node} node
164164
* @param {AddComment} addComment
165165
* @param {import('../iterateJsdoc.js').Context[]} ctxts
166+
* @param {Token} [locComment] Comment to anchor the report location to,
167+
* e.g., the first comment of a stacked group of line comments, so the
168+
* report does not read as though only the last line were at fault.
166169
*/
167-
const reportings = (comment, node, addComment, ctxts) => {
170+
const reportings = (comment, node, addComment, ctxts, locComment) => {
168171
const fixer = getFixer(node, comment, addComment, ctxts);
169172

170173
if (comment.type === 'Block') {
@@ -181,33 +184,89 @@ export default {
181184
return;
182185
}
183186

184-
report('lineCommentsJsdocStyle', comment, node, fixer);
187+
report('lineCommentsJsdocStyle', locComment ?? comment, node, fixer);
185188
}
186189
};
187190

191+
/**
192+
* Walks backward from a `//` comment which immediately precedes a node,
193+
* collecting any directly adjacent (no intervening blank line) `//`
194+
* comments stacked above it, so that the fixer can convert the whole
195+
* run into a single JSDoc block instead of leaving all but the last
196+
* line behind.
197+
* @param {Token} comment
198+
* @returns {Token[]}
199+
*/
200+
const getPrecedingLineCommentGroup = (comment) => {
201+
const group = [
202+
comment,
203+
];
204+
let current = comment;
205+
206+
for (;;) {
207+
const prev = /** @type {Token|null} */ (
208+
sourceCode.getTokenBefore(
209+
/** @type {import('eslint').AST.Token} */ (current),
210+
{
211+
includeComments: true,
212+
},
213+
)
214+
);
215+
216+
if (
217+
!prev ||
218+
prev.type !== 'Line' ||
219+
// @ts-expect-error Ok
220+
prev.loc.end.line !== current.loc.start.line - 1 ||
221+
/** @type {string[]} */
222+
(allowedPrefixes).some((prefix) => {
223+
return prev.value.trimStart().startsWith(prefix);
224+
})
225+
) {
226+
break;
227+
}
228+
229+
group.unshift(prev);
230+
current = prev;
231+
}
232+
233+
return group;
234+
};
235+
188236
/**
189237
* Builds the opening portion of the JSDoc comment, i.e. everything before
190-
* the closing delimiter.
238+
* the closing delimiter. When more than one comment is supplied (e.g., a
239+
* stacked group of `//` lines), each is rendered on its own JSDoc line.
191240
* @param {string} indent
192-
* @param {Token} comment
241+
* @param {Token[]} comments
193242
* @param {boolean|undefined} inlineCommentBlock
194243
* @returns {string}
195244
*/
196-
const getCommentOpening = (indent, comment, inlineCommentBlock) => {
245+
const getCommentOpening = (indent, comments, inlineCommentBlock) => {
197246
if (inlineCommentBlock || enforceJsdocLineStyle === 'single') {
198-
return `/** ${comment.value.trim()} `;
247+
return `/** ${comments.map((comment) => {
248+
return comment.value.trim();
249+
}).join(' ')} `;
199250
}
200251

201-
const body = comment.value.trimEnd();
252+
if (comments.length === 1) {
253+
const body = comments[0].value.trimEnd();
254+
255+
// When the comment's text already begins on its own line (e.g. a
256+
// multi-line block comment), there is no need for the fixer to add a
257+
// leading blank `*` line.
258+
if ((/^[ \t]*\n/v).test(body)) {
259+
return `/**${body.replace(/^[ \t]+/v, '')}\n${indent}`;
260+
}
202261

203-
// When the comment's text already begins on its own line (e.g. a
204-
// multi-line block comment), there is no need for the fixer to add a
205-
// leading blank `*` line.
206-
if ((/^[ \t]*\n/v).test(body)) {
207-
return `/**${body.replace(/^[ \t]+/v, '')}\n${indent}`;
262+
return `/**\n${indent}*${body}\n${indent}`;
208263
}
209264

210-
return `/**\n${indent}*${body}\n${indent}`;
265+
const inner = comments.map((comment) => {
266+
return `${indent}*${comment.value.trimEnd()}`;
267+
}).join('\n');
268+
269+
return `/**\n${inner}\n${indent}`;
211270
};
212271

213272
/**
@@ -228,19 +287,29 @@ export default {
228287

229288
reportingNonJsdoc = true;
230289

290+
const commentGroup = comment.type === 'Line' ?
291+
getPrecedingLineCommentGroup(/** @type {Token} */ (comment)) :
292+
[
293+
/** @type {Token} */ (comment),
294+
];
295+
231296
/** @type {AddComment} */
232297
const addComment = (inlineCommentBlock, commentToAdd, indent, lines, fixer) => {
233-
const insertion = getCommentOpening(indent, commentToAdd, inlineCommentBlock) +
298+
const insertion = getCommentOpening(indent, commentGroup, inlineCommentBlock) +
234299
`*/${'\n'.repeat((lines || 1) - 1)}`;
235300

236-
return fixer.replaceText(
237-
/** @type {import('eslint').AST.Token} */
238-
(commentToAdd),
301+
return fixer.replaceTextRange(
302+
[
303+
/* c8 ignore next -- Guard */
304+
commentGroup[0].range?.[0] ?? 0,
305+
/* c8 ignore next -- Guard */
306+
commentToAdd.range?.[1] ?? 0,
307+
],
239308
insertion,
240309
);
241310
};
242311

243-
reportings(comment, node, addComment, contexts);
312+
reportings(comment, node, addComment, contexts, commentGroup[0]);
244313
};
245314

246315
/**
@@ -263,7 +332,9 @@ export default {
263332

264333
/** @type {AddComment} */
265334
const addComment = (inlineCommentBlock, commentToAdd, indent, lines, fixer) => {
266-
const insertion = getCommentOpening(indent, commentToAdd, inlineCommentBlock) +
335+
const insertion = getCommentOpening(indent, [
336+
/** @type {Token} */ (commentToAdd),
337+
], inlineCommentBlock) +
267338
`*/${'\n'.repeat((lines || 1) - 1)}${lines ? `\n${indent.slice(1)}` : ' '}`;
268339

269340
return [

‎test/rules/assertions/convertToJsdocComments.js‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,108 @@ export default /** @type {import('../index.js').TestCases} */ ({
535535
const SENIORITY_ORDER = ['senior', 'middle', 'specialist'];
536536
`,
537537
},
538+
{
539+
code: `
540+
// one
541+
// two
542+
// three
543+
type Foo = string;
544+
`,
545+
errors: [
546+
{
547+
line: 2,
548+
message: 'Line comments should be JSDoc-style.',
549+
},
550+
],
551+
languageOptions: {
552+
parser: typescriptEslintParser,
553+
sourceType: 'module',
554+
},
555+
options: [
556+
{
557+
contexts: [
558+
'TSTypeAliasDeclaration',
559+
],
560+
},
561+
],
562+
output: `
563+
/**
564+
* one
565+
* two
566+
* three
567+
*/
568+
type Foo = string;
569+
`,
570+
},
571+
{
572+
code: `
573+
// one
574+
// two
575+
// three
576+
function quux () {}
577+
`,
578+
errors: [
579+
{
580+
line: 2,
581+
message: 'Line comments should be JSDoc-style.',
582+
},
583+
],
584+
options: [
585+
{
586+
enforceJsdocLineStyle: 'single',
587+
},
588+
],
589+
output: `
590+
/** one two three */
591+
function quux () {}
592+
`,
593+
},
594+
{
595+
code: `
596+
// separate paragraph
597+
598+
// one
599+
// two
600+
function quux () {}
601+
`,
602+
errors: [
603+
{
604+
line: 4,
605+
message: 'Line comments should be JSDoc-style.',
606+
},
607+
],
608+
output: `
609+
// separate paragraph
610+
611+
/**
612+
* one
613+
* two
614+
*/
615+
function quux () {}
616+
`,
617+
},
618+
{
619+
code: `
620+
// eslint-disable-next-line no-magic-numbers
621+
// one
622+
// two
623+
function quux () {}
624+
`,
625+
errors: [
626+
{
627+
line: 3,
628+
message: 'Line comments should be JSDoc-style.',
629+
},
630+
],
631+
output: `
632+
// eslint-disable-next-line no-magic-numbers
633+
/**
634+
* one
635+
* two
636+
*/
637+
function quux () {}
638+
`,
639+
},
538640
],
539641
valid: [
540642
{

0 commit comments

Comments
 (0)