empty_comment.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  2. # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
  3. # Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt
  4. from __future__ import annotations
  5. from typing import TYPE_CHECKING
  6. from astroid import nodes
  7. from pylint.checkers import BaseRawFileChecker
  8. if TYPE_CHECKING:
  9. from pylint.lint import PyLinter
  10. def is_line_commented(line: bytes) -> bool:
  11. """Checks if a `# symbol that is not part of a string was found in line."""
  12. comment_idx = line.find(b"#")
  13. if comment_idx == -1:
  14. return False
  15. if comment_part_of_string(line, comment_idx):
  16. return is_line_commented(line[:comment_idx] + line[comment_idx + 1 :])
  17. return True
  18. def comment_part_of_string(line: bytes, comment_idx: int) -> bool:
  19. """Checks if the symbol at comment_idx is part of a string."""
  20. if (
  21. line[:comment_idx].count(b"'") % 2 == 1
  22. and line[comment_idx:].count(b"'") % 2 == 1
  23. ) or (
  24. line[:comment_idx].count(b'"') % 2 == 1
  25. and line[comment_idx:].count(b'"') % 2 == 1
  26. ):
  27. return True
  28. return False
  29. class CommentChecker(BaseRawFileChecker):
  30. name = "empty-comment"
  31. msgs = {
  32. "R2044": (
  33. "Line with empty comment",
  34. "empty-comment",
  35. (
  36. "Used when a # symbol appears on a line not followed by an actual comment"
  37. ),
  38. )
  39. }
  40. options = ()
  41. def process_module(self, node: nodes.Module) -> None:
  42. with node.stream() as stream:
  43. for line_num, line in enumerate(stream):
  44. line = line.rstrip()
  45. if line.endswith(b"#"):
  46. if not is_line_commented(line[:-1]):
  47. self.add_message("empty-comment", line=line_num + 1)
  48. def register(linter: PyLinter) -> None:
  49. linter.register_checker(CommentChecker(linter))