Skip to content

Preserve trailing comments on kept imports in UnusedImportRefactor#154

Merged
RadikalJin merged 1 commit into
mainfrom
feature/unused-import-comment-preservation
Jun 10, 2026
Merged

Preserve trailing comments on kept imports in UnusedImportRefactor#154
RadikalJin merged 1 commit into
mainfrom
feature/unused-import-comment-preservation

Conversation

@RadikalJin

Copy link
Copy Markdown
Member

Unused imports are always removed, including those with trailing same-line comments (e.g. // NOPMD, // NOSONAR). Used imports that carry a trailing comment have their comment preserved through the sort: the verbatim source text is emitted via a string placeholder on re-insertion.

Implementation notes:

  • CompilationUnitProperty.SOURCE stores the original source text on the compilation unit so comment text can be extracted by position without file I/O.
  • Comment detection scans the remainder of the import's line in the source string for a '//' prefix (getCommentList() is not populated in standalone ASTParser mode).
  • run() returns early for non-top-level-type nodes to avoid re-processing the import list on subsequent visitor callbacks for inner classes etc.

Adds ImportWithTrailingCommentExample / ...After golden-file test and a corresponding test method in TestImportsRefactor.

Unused imports are always removed, including those with trailing same-line
comments (e.g. // NOPMD, // NOSONAR). Used imports that carry a trailing
comment have their comment preserved through the sort: the verbatim source
text is emitted via a string placeholder on re-insertion.

Implementation notes:
- CompilationUnitProperty.SOURCE stores the original source text on the
  compilation unit so comment text can be extracted by position without
  file I/O.
- Comment detection scans the remainder of the import's line in the
  source string for a '//' prefix (getCommentList() is not populated in
  standalone ASTParser mode).
- run() returns early for non-top-level-type nodes to avoid re-processing
  the import list on subsequent visitor callbacks for inner classes etc.

Adds ImportWithTrailingCommentExample / ...After golden-file test and a
corresponding test method in TestImportsRefactor.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@RadikalJin RadikalJin merged commit 5f284de into main Jun 10, 2026
2 checks passed
@RadikalJin RadikalJin deleted the feature/unused-import-comment-preservation branch June 10, 2026 12:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant