exceptions.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. """All isort specific exception classes should be defined here"""
  2. from functools import partial
  3. from pathlib import Path
  4. from typing import Any, Dict, List, Type, Union
  5. from .profiles import profiles
  6. class ISortError(Exception):
  7. """Base isort exception object from which all isort sourced exceptions should inherit"""
  8. def __reduce__(self): # type: ignore
  9. return (partial(type(self), **self.__dict__), ())
  10. class InvalidSettingsPath(ISortError):
  11. """Raised when a settings path is provided that is neither a valid file or directory"""
  12. def __init__(self, settings_path: str):
  13. super().__init__(
  14. f"isort was told to use the settings_path: {settings_path} as the base directory or "
  15. "file that represents the starting point of config file discovery, but it does not "
  16. "exist."
  17. )
  18. self.settings_path = settings_path
  19. class ExistingSyntaxErrors(ISortError):
  20. """Raised when isort is told to sort imports within code that has existing syntax errors"""
  21. def __init__(self, file_path: str):
  22. super().__init__(
  23. f"isort was told to sort imports within code that contains syntax errors: "
  24. f"{file_path}."
  25. )
  26. self.file_path = file_path
  27. class IntroducedSyntaxErrors(ISortError):
  28. """Raised when isort has introduced a syntax error in the process of sorting imports"""
  29. def __init__(self, file_path: str):
  30. super().__init__(
  31. f"isort introduced syntax errors when attempting to sort the imports contained within "
  32. f"{file_path}."
  33. )
  34. self.file_path = file_path
  35. class FileSkipped(ISortError):
  36. """Should be raised when a file is skipped for any reason"""
  37. def __init__(self, message: str, file_path: str):
  38. super().__init__(message)
  39. self.message = message
  40. self.file_path = file_path
  41. class FileSkipComment(FileSkipped):
  42. """Raised when an entire file is skipped due to a isort skip file comment"""
  43. def __init__(self, file_path: str, **kwargs: str):
  44. super().__init__(
  45. f"{file_path} contains a file skip comment and was skipped.", file_path=file_path
  46. )
  47. class FileSkipSetting(FileSkipped):
  48. """Raised when an entire file is skipped due to provided isort settings"""
  49. def __init__(self, file_path: str, **kwargs: str):
  50. super().__init__(
  51. f"{file_path} was skipped as it's listed in 'skip' setting"
  52. " or matches a glob in 'skip_glob' setting",
  53. file_path=file_path,
  54. )
  55. class ProfileDoesNotExist(ISortError):
  56. """Raised when a profile is set by the user that doesn't exist"""
  57. def __init__(self, profile: str):
  58. super().__init__(
  59. f"Specified profile of {profile} does not exist. "
  60. f"Available profiles: {','.join(profiles)}."
  61. )
  62. self.profile = profile
  63. class SortingFunctionDoesNotExist(ISortError):
  64. """Raised when the specified sorting function isn't available"""
  65. def __init__(self, sort_order: str, available_sort_orders: List[str]):
  66. super().__init__(
  67. f"Specified sort_order of {sort_order} does not exist. "
  68. f"Available sort_orders: {','.join(available_sort_orders)}."
  69. )
  70. self.sort_order = sort_order
  71. self.available_sort_orders = available_sort_orders
  72. class FormattingPluginDoesNotExist(ISortError):
  73. """Raised when a formatting plugin is set by the user that doesn't exist"""
  74. def __init__(self, formatter: str):
  75. super().__init__(f"Specified formatting plugin of {formatter} does not exist. ")
  76. self.formatter = formatter
  77. class LiteralParsingFailure(ISortError):
  78. """Raised when one of isorts literal sorting comments is used but isort can't parse the
  79. the given data structure.
  80. """
  81. def __init__(self, code: str, original_error: Union[Exception, Type[Exception]]):
  82. super().__init__(
  83. f"isort failed to parse the given literal {code}. It's important to note "
  84. "that isort literal sorting only supports simple literals parsable by "
  85. f"ast.literal_eval which gave the exception of {original_error}."
  86. )
  87. self.code = code
  88. self.original_error = original_error
  89. class LiteralSortTypeMismatch(ISortError):
  90. """Raised when an isort literal sorting comment is used, with a type that doesn't match the
  91. supplied data structure's type.
  92. """
  93. def __init__(self, kind: type, expected_kind: type):
  94. super().__init__(
  95. f"isort was told to sort a literal of type {expected_kind} but was given "
  96. f"a literal of type {kind}."
  97. )
  98. self.kind = kind
  99. self.expected_kind = expected_kind
  100. class AssignmentsFormatMismatch(ISortError):
  101. """Raised when isort is told to sort assignments but the format of the assignment section
  102. doesn't match isort's expectation.
  103. """
  104. def __init__(self, code: str):
  105. super().__init__(
  106. "isort was told to sort a section of assignments, however the given code:\n\n"
  107. f"{code}\n\n"
  108. "Does not match isort's strict single line formatting requirement for assignment "
  109. "sorting:\n\n"
  110. "{variable_name} = {value}\n"
  111. "{variable_name2} = {value2}\n"
  112. "...\n\n"
  113. )
  114. self.code = code
  115. class UnsupportedSettings(ISortError):
  116. """Raised when settings are passed into isort (either from config, CLI, or runtime)
  117. that it doesn't support.
  118. """
  119. @staticmethod
  120. def _format_option(name: str, value: Any, source: str) -> str:
  121. return f"\t- {name} = {value} (source: '{source}')"
  122. def __init__(self, unsupported_settings: Dict[str, Dict[str, str]]):
  123. errors = "\n".join(
  124. self._format_option(name, **option) for name, option in unsupported_settings.items()
  125. )
  126. super().__init__(
  127. "isort was provided settings that it doesn't support:\n\n"
  128. f"{errors}\n\n"
  129. "For a complete and up-to-date listing of supported settings see: "
  130. "https://pycqa.github.io/isort/docs/configuration/options.\n"
  131. )
  132. self.unsupported_settings = unsupported_settings
  133. class UnsupportedEncoding(ISortError):
  134. """Raised when isort encounters an encoding error while trying to read a file"""
  135. def __init__(self, filename: Union[str, Path]):
  136. super().__init__(f"Unknown or unsupported encoding in {filename}")
  137. self.filename = filename
  138. class MissingSection(ISortError):
  139. """Raised when isort encounters an import that matches a section that is not defined"""
  140. def __init__(self, import_module: str, section: str):
  141. super().__init__(
  142. f"Found {import_module} import while parsing, but {section} was not included "
  143. "in the `sections` setting of your config. Please add it before continuing\n"
  144. "See https://pycqa.github.io/isort/#custom-sections-and-ordering "
  145. "for more info."
  146. )