empty_comment.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from astroid import nodes
  2. from pylint.checkers import BaseChecker
  3. from pylint.interfaces import IRawChecker
  4. def is_line_commented(line):
  5. """Checks if a `# symbol that is not part of a string was found in line"""
  6. comment_idx = line.find(b"#")
  7. if comment_idx == -1:
  8. return False
  9. if comment_part_of_string(line, comment_idx):
  10. return is_line_commented(line[:comment_idx] + line[comment_idx + 1 :])
  11. return True
  12. def comment_part_of_string(line, comment_idx):
  13. """checks if the symbol at comment_idx is part of a string"""
  14. if (
  15. line[:comment_idx].count(b"'") % 2 == 1
  16. and line[comment_idx:].count(b"'") % 2 == 1
  17. ) or (
  18. line[:comment_idx].count(b'"') % 2 == 1
  19. and line[comment_idx:].count(b'"') % 2 == 1
  20. ):
  21. return True
  22. return False
  23. class CommentChecker(BaseChecker):
  24. __implements__ = IRawChecker
  25. name = "refactoring"
  26. msgs = {
  27. "R2044": (
  28. "Line with empty comment",
  29. "empty-comment",
  30. (
  31. "Used when a # symbol appears on a line not followed by an actual comment"
  32. ),
  33. )
  34. }
  35. options = ()
  36. priority = -1 # low priority
  37. def process_module(self, node: nodes.Module) -> None:
  38. with node.stream() as stream:
  39. for (line_num, line) in enumerate(stream):
  40. line = line.rstrip()
  41. if line.endswith(b"#"):
  42. if not is_line_commented(line[:-1]):
  43. self.add_message("empty-comment", line=line_num + 1)
  44. def register(linter):
  45. linter.register_checker(CommentChecker(linter))