comments.py 887 B

1234567891011121314151617181920212223242526272829
  1. def parse(line: str) -> tuple[str, str]:
  2. """Parses import lines for comments and returns back the
  3. import statement and the associated comment.
  4. """
  5. comment_start = line.find("#")
  6. if comment_start != -1:
  7. return (line[:comment_start], line[comment_start + 1 :].strip())
  8. return (line, "")
  9. def add_to_line(
  10. comments: list[str] | None,
  11. original_string: str = "",
  12. removed: bool = False,
  13. comment_prefix: str = "",
  14. ) -> str:
  15. """Returns a string with comments added if removed is not set."""
  16. if removed:
  17. return parse(original_string)[0]
  18. if not comments:
  19. return original_string
  20. unique_comments: list[str] = []
  21. for comment in comments:
  22. if comment not in unique_comments:
  23. unique_comments.append(comment)
  24. return f"{parse(original_string)[0]}{comment_prefix} {'; '.join(unique_comments)}"