comments.py 933 B

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