|
| 1 | +import os |
| 2 | +import re |
| 3 | +import threading |
| 4 | +from pathlib import Path |
| 5 | +from typing import ( |
| 6 | + Any, |
| 7 | + Callable, |
| 8 | + Dict, |
| 9 | + Final, |
| 10 | + Iterator, |
| 11 | + List, |
| 12 | + Optional, |
| 13 | + Union, |
| 14 | +) |
| 15 | + |
| 16 | +from .event import event |
| 17 | +from .language import LanguageDefinition, language_id_filter |
| 18 | +from .lsp.types import DocumentUri |
| 19 | +from .text_document import TextDocument |
| 20 | +from .uri import Uri |
| 21 | +from .utils.logging import LoggingDescriptor |
| 22 | + |
| 23 | + |
| 24 | +class CantReadDocumentError(Exception): |
| 25 | + pass |
| 26 | + |
| 27 | + |
| 28 | +class DocumentsManager: |
| 29 | + _logger: Final = LoggingDescriptor() |
| 30 | + |
| 31 | + def __init__(self, languages: List[LanguageDefinition]) -> None: |
| 32 | + self.languages = languages |
| 33 | + |
| 34 | + self._documents: Dict[DocumentUri, TextDocument] = {} |
| 35 | + self._lock = threading.RLock() |
| 36 | + |
| 37 | + @property |
| 38 | + def documents(self) -> List[TextDocument]: |
| 39 | + return list(self._documents.values()) |
| 40 | + |
| 41 | + __NORMALIZE_LINE_ENDINGS: Final = re.compile(r"(\r?\n)") |
| 42 | + |
| 43 | + @classmethod |
| 44 | + def _normalize_line_endings(cls, text: str) -> str: |
| 45 | + return cls.__NORMALIZE_LINE_ENDINGS.sub("\n", text) |
| 46 | + |
| 47 | + def read_document_text(self, uri: Uri, language_id: Union[str, Callable[[Any], bool], None]) -> str: |
| 48 | + for e in self.on_read_document_text( |
| 49 | + self, |
| 50 | + uri, |
| 51 | + callback_filter=language_id_filter(language_id) if isinstance(language_id, str) else language_id, |
| 52 | + ): |
| 53 | + if isinstance(e, BaseException): |
| 54 | + raise RuntimeError(f"Can't read document text from {uri}: {e}") from e |
| 55 | + |
| 56 | + if e is not None: |
| 57 | + return self._normalize_line_endings(e) |
| 58 | + |
| 59 | + raise FileNotFoundError(str(uri)) |
| 60 | + |
| 61 | + def detect_language_id(self, path_or_uri: Union[str, "os.PathLike[Any]", Uri]) -> str: |
| 62 | + path = path_or_uri.to_path() if isinstance(path_or_uri, Uri) else Path(path_or_uri) |
| 63 | + |
| 64 | + for lang in self.languages: |
| 65 | + suffix = path.suffix |
| 66 | + if lang.extensions_ignore_case: |
| 67 | + suffix = suffix.lower() |
| 68 | + if suffix in lang.extensions: |
| 69 | + return lang.id |
| 70 | + |
| 71 | + return "unknown" |
| 72 | + |
| 73 | + @_logger.call |
| 74 | + def get_or_open_document( |
| 75 | + self, |
| 76 | + path: Union[str, "os.PathLike[Any]"], |
| 77 | + language_id: Optional[str] = None, |
| 78 | + version: Optional[int] = None, |
| 79 | + ) -> TextDocument: |
| 80 | + uri = Uri.from_path(path).normalized() |
| 81 | + |
| 82 | + result = self.get(uri) |
| 83 | + if result is not None: |
| 84 | + return result |
| 85 | + |
| 86 | + try: |
| 87 | + return self._append_document( |
| 88 | + document_uri=DocumentUri(uri), |
| 89 | + language_id=language_id or self.detect_language_id(path), |
| 90 | + text=self.read_document_text(uri, language_id), |
| 91 | + version=version, |
| 92 | + ) |
| 93 | + except (SystemExit, KeyboardInterrupt): |
| 94 | + raise |
| 95 | + except BaseException as e: |
| 96 | + raise CantReadDocumentError(f"Error reading document '{path}': {e!s}") from e |
| 97 | + |
| 98 | + @event |
| 99 | + def on_read_document_text(sender, uri: Uri) -> Optional[str]: |
| 100 | + ... |
| 101 | + |
| 102 | + @event |
| 103 | + def did_create_uri(sender, uri: DocumentUri) -> None: |
| 104 | + ... |
| 105 | + |
| 106 | + @event |
| 107 | + def did_create(sender, document: TextDocument) -> None: |
| 108 | + ... |
| 109 | + |
| 110 | + @event |
| 111 | + def did_open(sender, document: TextDocument) -> None: |
| 112 | + ... |
| 113 | + |
| 114 | + @event |
| 115 | + def did_close(sender, document: TextDocument, full_close: bool) -> None: |
| 116 | + ... |
| 117 | + |
| 118 | + @event |
| 119 | + def did_change(sender, document: TextDocument) -> None: |
| 120 | + ... |
| 121 | + |
| 122 | + @event |
| 123 | + def did_save(sender, document: TextDocument) -> None: |
| 124 | + ... |
| 125 | + |
| 126 | + def get(self, _uri: Union[DocumentUri, Uri]) -> Optional[TextDocument]: |
| 127 | + with self._lock: |
| 128 | + return self._documents.get( |
| 129 | + str(Uri(_uri).normalized() if not isinstance(_uri, Uri) else _uri), |
| 130 | + None, |
| 131 | + ) |
| 132 | + |
| 133 | + def __len__(self) -> int: |
| 134 | + return self._documents.__len__() |
| 135 | + |
| 136 | + def __iter__(self) -> Iterator[DocumentUri]: |
| 137 | + return self._documents.__iter__() |
| 138 | + |
| 139 | + @event |
| 140 | + def on_document_cache_invalidate(sender, document: TextDocument) -> None: |
| 141 | + ... |
| 142 | + |
| 143 | + def _on_document_cache_invalidate(self, sender: TextDocument) -> None: |
| 144 | + self.on_document_cache_invalidate(self, sender) |
| 145 | + |
| 146 | + @event |
| 147 | + def on_document_cache_invalidated(sender, document: TextDocument) -> None: |
| 148 | + ... |
| 149 | + |
| 150 | + def _on_document_cache_invalidated(self, sender: TextDocument) -> None: |
| 151 | + self.on_document_cache_invalidated(self, sender) |
| 152 | + |
| 153 | + def _create_document( |
| 154 | + self, |
| 155 | + document_uri: DocumentUri, |
| 156 | + text: str, |
| 157 | + language_id: Optional[str] = None, |
| 158 | + version: Optional[int] = None, |
| 159 | + ) -> TextDocument: |
| 160 | + result = TextDocument( |
| 161 | + document_uri=document_uri, |
| 162 | + language_id=language_id, |
| 163 | + text=text, |
| 164 | + version=version, |
| 165 | + ) |
| 166 | + |
| 167 | + result.cache_invalidate.add(self._on_document_cache_invalidate) |
| 168 | + result.cache_invalidated.add(self._on_document_cache_invalidated) |
| 169 | + |
| 170 | + return result |
| 171 | + |
| 172 | + def _append_document( |
| 173 | + self, |
| 174 | + document_uri: DocumentUri, |
| 175 | + language_id: str, |
| 176 | + text: str, |
| 177 | + version: Optional[int] = None, |
| 178 | + ) -> TextDocument: |
| 179 | + with self._lock: |
| 180 | + document = self._create_document( |
| 181 | + document_uri=document_uri, |
| 182 | + language_id=language_id, |
| 183 | + text=text, |
| 184 | + version=version, |
| 185 | + ) |
| 186 | + |
| 187 | + self._documents[document_uri] = document |
| 188 | + |
| 189 | + return document |
| 190 | + |
| 191 | + @_logger.call |
| 192 | + def close_document(self, document: TextDocument, real_close: bool = False) -> None: |
| 193 | + document._version = None |
| 194 | + |
| 195 | + if real_close: |
| 196 | + with self._lock: |
| 197 | + self._documents.pop(str(document.uri), None) |
| 198 | + |
| 199 | + document.clear() |
| 200 | + else: |
| 201 | + if document.revert(None): |
| 202 | + self.did_change(self, document, callback_filter=language_id_filter(document)) |
| 203 | + |
| 204 | + self.did_close(self, document, real_close, callback_filter=language_id_filter(document)) |
0 commit comments