deepnote-python-lsp-server 0.0.0__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. deepnote_python_lsp_server-0.0.0.dist-info/METADATA +263 -0
  2. deepnote_python_lsp_server-0.0.0.dist-info/RECORD +43 -0
  3. deepnote_python_lsp_server-0.0.0.dist-info/WHEEL +6 -0
  4. deepnote_python_lsp_server-0.0.0.dist-info/entry_points.txt +24 -0
  5. deepnote_python_lsp_server-0.0.0.dist-info/licenses/LICENSE +22 -0
  6. deepnote_python_lsp_server-0.0.0.dist-info/top_level.txt +1 -0
  7. pylsp/__init__.py +33 -0
  8. pylsp/__main__.py +132 -0
  9. pylsp/_utils.py +325 -0
  10. pylsp/config/__init__.py +2 -0
  11. pylsp/config/config.py +202 -0
  12. pylsp/config/flake8_conf.py +64 -0
  13. pylsp/config/pycodestyle_conf.py +34 -0
  14. pylsp/config/source.py +88 -0
  15. pylsp/hookspecs.py +140 -0
  16. pylsp/lsp.py +115 -0
  17. pylsp/plugins/__init__.py +2 -0
  18. pylsp/plugins/_resolvers.py +132 -0
  19. pylsp/plugins/_rope_task_handle.py +106 -0
  20. pylsp/plugins/autopep8_format.py +95 -0
  21. pylsp/plugins/definition.py +84 -0
  22. pylsp/plugins/flake8_lint.py +243 -0
  23. pylsp/plugins/folding.py +210 -0
  24. pylsp/plugins/highlight.py +36 -0
  25. pylsp/plugins/hover.py +57 -0
  26. pylsp/plugins/jedi_completion.py +318 -0
  27. pylsp/plugins/jedi_rename.py +56 -0
  28. pylsp/plugins/mccabe_lint.py +56 -0
  29. pylsp/plugins/preload_imports.py +38 -0
  30. pylsp/plugins/pycodestyle_lint.py +113 -0
  31. pylsp/plugins/pydocstyle_lint.py +127 -0
  32. pylsp/plugins/pyflakes_lint.py +97 -0
  33. pylsp/plugins/pylint_lint.py +367 -0
  34. pylsp/plugins/references.py +33 -0
  35. pylsp/plugins/rope_autoimport.py +407 -0
  36. pylsp/plugins/rope_completion.py +161 -0
  37. pylsp/plugins/signature.py +81 -0
  38. pylsp/plugins/symbols.py +214 -0
  39. pylsp/plugins/yapf_format.py +199 -0
  40. pylsp/python_lsp.py +921 -0
  41. pylsp/text_edit.py +97 -0
  42. pylsp/uris.py +139 -0
  43. pylsp/workspace.py +730 -0
pylsp/workspace.py ADDED
@@ -0,0 +1,730 @@
1
+ # Copyright 2017-2020 Palantir Technologies, Inc.
2
+ # Copyright 2021- Python Language Server Contributors.
3
+
4
+ import functools
5
+ import io
6
+ import logging
7
+ import os
8
+ import re
9
+ import uuid
10
+ from contextlib import contextmanager
11
+ from threading import RLock
12
+ from typing import Callable, Generator, List, Optional
13
+ import importlib.metadata
14
+
15
+ import jedi
16
+
17
+ from . import _utils, lsp, uris
18
+
19
+ log = logging.getLogger(__name__)
20
+
21
+ DEFAULT_AUTO_IMPORT_MODULES = ["numpy"]
22
+
23
+ # TODO: this is not the best e.g. we capture numbers
24
+ RE_START_WORD = re.compile("[A-Za-z_0-9]*$")
25
+ RE_END_WORD = re.compile("^[A-Za-z_0-9]*")
26
+
27
+
28
+ def lock(method):
29
+ """Define an atomic region over a method."""
30
+
31
+ @functools.wraps(method)
32
+ def wrapper(self, *args, **kwargs):
33
+ with self._lock:
34
+ return method(self, *args, **kwargs)
35
+
36
+ return wrapper
37
+
38
+
39
+ class Workspace:
40
+ M_PUBLISH_DIAGNOSTICS = "textDocument/publishDiagnostics"
41
+ M_PROGRESS = "$/progress"
42
+ M_INITIALIZE_PROGRESS = "window/workDoneProgress/create"
43
+ M_APPLY_EDIT = "workspace/applyEdit"
44
+ M_SHOW_MESSAGE = "window/showMessage"
45
+ M_LOG_MESSAGE = "window/logMessage"
46
+
47
+ def __init__(self, root_uri, endpoint, config=None) -> None:
48
+ self._config = config
49
+ self._root_uri = root_uri
50
+ self._endpoint = endpoint
51
+ self._root_uri_scheme = uris.urlparse(self._root_uri)[0]
52
+ self._root_path = uris.to_fs_path(self._root_uri)
53
+ self._docs = {}
54
+
55
+ # Cache jedi environments
56
+ self._environments = {}
57
+
58
+ # Whilst incubating, keep rope private
59
+ self.__rope = None
60
+ self.__rope_config = None
61
+ self.__rope_autoimport = None
62
+
63
+ def _rope_autoimport(
64
+ self,
65
+ rope_config: Optional,
66
+ memory: bool = False,
67
+ ):
68
+ from rope.contrib.autoimport.sqlite import AutoImport
69
+
70
+ if self.__rope_autoimport is None:
71
+ project = self._rope_project_builder(rope_config)
72
+ self.__rope_autoimport = AutoImport(project, memory=memory)
73
+ return self.__rope_autoimport
74
+
75
+ def _rope_project_builder(self, rope_config):
76
+ from rope.base.project import Project
77
+
78
+ # TODO: we could keep track of dirty files and validate only those
79
+ if self.__rope is None or self.__rope_config != rope_config:
80
+ rope_folder = rope_config.get("ropeFolder")
81
+ if "ropeFolder" in rope_config:
82
+ self.__rope = Project(self._root_path, ropefolder=rope_folder)
83
+ else:
84
+ self.__rope = Project(self._root_path)
85
+ self.__rope.prefs.set(
86
+ "extension_modules", rope_config.get("extensionModules", [])
87
+ )
88
+ self.__rope.prefs.set("ignore_syntax_errors", True)
89
+ self.__rope.prefs.set("ignore_bad_imports", True)
90
+ self.__rope.validate()
91
+ return self.__rope
92
+
93
+ @property
94
+ def documents(self):
95
+ return self._docs
96
+
97
+ @property
98
+ def root_path(self):
99
+ return self._root_path
100
+
101
+ @property
102
+ def root_uri(self):
103
+ return self._root_uri
104
+
105
+ def is_local(self):
106
+ return (self._root_uri_scheme in ["", "file"]) and os.path.exists(
107
+ self._root_path
108
+ )
109
+
110
+ def get_document(self, doc_uri):
111
+ """Return a managed document if-present, else create one pointing at disk.
112
+
113
+ See https://github.com/Microsoft/language-server-protocol/issues/177
114
+ """
115
+ return self._docs.get(doc_uri) or self._create_document(doc_uri)
116
+
117
+ def get_cell_document(self, doc_uri):
118
+ return self._docs.get(doc_uri)
119
+
120
+ def get_maybe_document(self, doc_uri):
121
+ return self._docs.get(doc_uri)
122
+
123
+ def put_document(self, doc_uri, source, version=None) -> None:
124
+ self._docs[doc_uri] = self._create_document(
125
+ doc_uri, source=source, version=version
126
+ )
127
+
128
+ def put_notebook_document(
129
+ self, doc_uri, notebook_type, cells, version=None, metadata=None
130
+ ) -> None:
131
+ self._docs[doc_uri] = self._create_notebook_document(
132
+ doc_uri, notebook_type, cells, version, metadata
133
+ )
134
+
135
+ @contextmanager
136
+ def temp_document(self, source, path=None) -> None:
137
+ if path is None:
138
+ path = self.root_path
139
+ uri = uris.from_fs_path(os.path.join(path, str(uuid.uuid4())))
140
+ try:
141
+ self.put_document(uri, source)
142
+ yield uri
143
+ finally:
144
+ self.rm_document(uri)
145
+
146
+ def add_notebook_cells(self, doc_uri, cells, start) -> None:
147
+ self._docs[doc_uri].add_cells(cells, start)
148
+
149
+ def remove_notebook_cells(self, doc_uri, start, delete_count) -> None:
150
+ self._docs[doc_uri].remove_cells(start, delete_count)
151
+
152
+ def update_notebook_metadata(self, doc_uri, metadata) -> None:
153
+ self._docs[doc_uri].metadata = metadata
154
+
155
+ def put_cell_document(
156
+ self, doc_uri, notebook_uri, language_id, source, version=None
157
+ ) -> None:
158
+ self._docs[doc_uri] = self._create_cell_document(
159
+ doc_uri, notebook_uri, language_id, source, version
160
+ )
161
+
162
+ def rm_document(self, doc_uri) -> None:
163
+ self._docs.pop(doc_uri)
164
+
165
+ def update_document(self, doc_uri, change, version=None) -> None:
166
+ self._docs[doc_uri].apply_change(change)
167
+ self._docs[doc_uri].version = version
168
+
169
+ def update_config(self, settings):
170
+ self._config.update((settings or {}).get("pylsp", {}))
171
+ for doc_uri in self.documents:
172
+ if isinstance(document := self.get_document(doc_uri), Notebook):
173
+ # Notebook documents don't have a config. The config is
174
+ # handled at the cell level.
175
+ return
176
+ document.update_config(settings)
177
+
178
+ def apply_edit(self, edit):
179
+ return self._endpoint.request(self.M_APPLY_EDIT, {"edit": edit})
180
+
181
+ def publish_diagnostics(self, doc_uri, diagnostics, doc_version=None) -> None:
182
+ params = {
183
+ "uri": doc_uri,
184
+ "diagnostics": diagnostics,
185
+ }
186
+
187
+ if doc_version:
188
+ params["version"] = doc_version
189
+
190
+ self._endpoint.notify(
191
+ self.M_PUBLISH_DIAGNOSTICS,
192
+ params=params,
193
+ )
194
+
195
+ @contextmanager
196
+ def report_progress(
197
+ self,
198
+ title: str,
199
+ message: Optional[str] = None,
200
+ percentage: Optional[int] = None,
201
+ skip_token_initialization: bool = False,
202
+ ) -> Generator[Callable[[str, Optional[int]], None], None, None]:
203
+ """
204
+ Report progress to the editor / client.
205
+
206
+ ``skip_token_initialization` is necessary due to some current
207
+ limitations of our LSP implementation. When `report_progress`
208
+ is used from a synchronous LSP handler, the token initialization
209
+ will time out because we can't receive the response.
210
+
211
+ Many editors will still correctly show the progress messages though, which
212
+ is why we are giving progress users the option to skip the initialization
213
+ of the progress token.
214
+ """
215
+ if self._config:
216
+ client_supports_progress_reporting = self._config.capabilities.get(
217
+ "window", {}
218
+ ).get("workDoneProgress", False)
219
+ else:
220
+ client_supports_progress_reporting = False
221
+
222
+ if client_supports_progress_reporting:
223
+ token = self._progress_begin(
224
+ title, message, percentage, skip_token_initialization
225
+ )
226
+
227
+ def progress_message(
228
+ message: str, percentage: Optional[int] = None
229
+ ) -> None:
230
+ self._progress_report(token, message, percentage)
231
+
232
+ try:
233
+ yield progress_message
234
+ finally:
235
+ self._progress_end(token)
236
+
237
+ return
238
+
239
+ # FALLBACK:
240
+ # If the client doesn't support progress reporting, we have a dummy method
241
+ # for the caller to use.
242
+ def dummy_progress_message(
243
+ message: str, percentage: Optional[int] = None
244
+ ) -> None:
245
+ pass
246
+
247
+ yield dummy_progress_message
248
+
249
+ def _progress_begin(
250
+ self,
251
+ title: str,
252
+ message: Optional[str] = None,
253
+ percentage: Optional[int] = None,
254
+ skip_token_initialization: bool = False,
255
+ ) -> str:
256
+ token = str(uuid.uuid4())
257
+
258
+ if not skip_token_initialization:
259
+ try:
260
+ self._endpoint.request(
261
+ self.M_INITIALIZE_PROGRESS, {"token": token}
262
+ ).result(timeout=1.0)
263
+ except Exception:
264
+ log.warning(
265
+ "There was an error while trying to initialize progress reporting."
266
+ "Likely progress reporting was used in a synchronous LSP handler, "
267
+ "which is not supported by progress reporting yet. "
268
+ "To prevent waiting for the timeout you can set "
269
+ "`skip_token_initialization=True`. "
270
+ "Not every editor will show progress then, but many will.",
271
+ exc_info=True,
272
+ )
273
+
274
+ value = {
275
+ "kind": "begin",
276
+ "title": title,
277
+ }
278
+ if message is not None:
279
+ value["message"] = message
280
+ if percentage is not None:
281
+ value["percentage"] = percentage
282
+
283
+ self._endpoint.notify(
284
+ self.M_PROGRESS,
285
+ params={
286
+ "token": token,
287
+ "value": value,
288
+ },
289
+ )
290
+ return token
291
+
292
+ def _progress_report(
293
+ self,
294
+ token: str,
295
+ message: Optional[str] = None,
296
+ percentage: Optional[int] = None,
297
+ ) -> None:
298
+ value = {
299
+ "kind": "report",
300
+ }
301
+ if message:
302
+ value["message"] = message
303
+ if percentage:
304
+ value["percentage"] = percentage
305
+
306
+ self._endpoint.notify(
307
+ self.M_PROGRESS,
308
+ params={
309
+ "token": token,
310
+ "value": value,
311
+ },
312
+ )
313
+
314
+ def _progress_end(self, token: str, message: Optional[str] = None) -> None:
315
+ value = {
316
+ "kind": "end",
317
+ }
318
+ if message:
319
+ value["message"] = message
320
+
321
+ self._endpoint.notify(
322
+ self.M_PROGRESS,
323
+ params={
324
+ "token": token,
325
+ "value": value,
326
+ },
327
+ )
328
+
329
+ def log_message(self, message, msg_type=lsp.MessageType.Info):
330
+ self._endpoint.notify(
331
+ self.M_LOG_MESSAGE, params={"type": msg_type, "message": message}
332
+ )
333
+
334
+ def show_message(self, message, msg_type=lsp.MessageType.Info) -> None:
335
+ self._endpoint.notify(
336
+ self.M_SHOW_MESSAGE, params={"type": msg_type, "message": message}
337
+ )
338
+
339
+ def source_roots(self, document_path):
340
+ """Return the source roots for the given document."""
341
+ files = (
342
+ _utils.find_parents(
343
+ self._root_path, document_path, ["setup.py", "pyproject.toml"]
344
+ )
345
+ or []
346
+ )
347
+ return list({os.path.dirname(project_file) for project_file in files}) or [
348
+ self._root_path
349
+ ]
350
+
351
+ def _create_document(self, doc_uri, source=None, version=None):
352
+ path = uris.to_fs_path(doc_uri)
353
+ return Document(
354
+ doc_uri,
355
+ self,
356
+ source=source,
357
+ version=version,
358
+ extra_sys_path=self.source_roots(path),
359
+ rope_project_builder=self._rope_project_builder,
360
+ )
361
+
362
+ def _create_notebook_document(
363
+ self, doc_uri, notebook_type, cells, version=None, metadata=None
364
+ ):
365
+ return Notebook(
366
+ doc_uri,
367
+ notebook_type,
368
+ self,
369
+ cells=cells,
370
+ version=version,
371
+ metadata=metadata,
372
+ )
373
+
374
+ def _create_cell_document(
375
+ self, doc_uri, notebook_uri, language_id, source=None, version=None
376
+ ):
377
+ # TODO: remove what is unnecessary here.
378
+ path = uris.to_fs_path(doc_uri)
379
+ return Cell(
380
+ doc_uri,
381
+ notebook_uri=notebook_uri,
382
+ language_id=language_id,
383
+ workspace=self,
384
+ source=source,
385
+ version=version,
386
+ extra_sys_path=self.source_roots(path),
387
+ rope_project_builder=self._rope_project_builder,
388
+ )
389
+
390
+ def close(self) -> None:
391
+ if self.__rope_autoimport:
392
+ self.__rope_autoimport.close()
393
+
394
+
395
+ class Document:
396
+ DO_NOT_PRELOAD_MODULES = ['attrs', 'backcall', 'bleach', 'certifi', 'chardet', 'cycler', 'decorator', 'defusedxml',
397
+ 'docopt', 'entrypoints', 'idna', 'importlib-metadata', 'ipykernel', 'ipython-genutils',
398
+ 'ipython', 'ipywidgets', 'jedi', 'jinja2', 'joblib', 'jsonschema', 'jupyter-client',
399
+ 'jupyter-core', 'markupsafe', 'mistune', 'nbconvert', 'nbformat', 'notebook', 'packaging',
400
+ 'pandocfilters', 'parso', 'pexpect', 'pickleshare', 'pip', 'pipreqs', 'pluggy',
401
+ 'prometheus-client', 'prompt-toolkit', 'ptyprocess', 'pygments', 'pyparsing',
402
+ 'pyrsistent', 'python-dateutil', 'python-jsonrpc-server', 'python-language-server',
403
+ 'pytz', 'pyzmq', 'send2trash', 'setuptools', 'six', 'terminado', 'testpath',
404
+ 'threadpoolctl', 'tornado', 'traitlets', 'ujson', 'wcwidth', 'webencodings', 'wheel',
405
+ 'widgetsnbextension', 'yarg', 'zipp']
406
+
407
+
408
+ def __init__(
409
+ self,
410
+ uri,
411
+ workspace,
412
+ source=None,
413
+ version=None,
414
+ local=True,
415
+ extra_sys_path=None,
416
+ rope_project_builder=None,
417
+ ) -> None:
418
+ self.uri = uri
419
+ self.version = version
420
+ self.path = uris.to_fs_path(uri)
421
+ self.dot_path = _utils.path_to_dot_name(self.path)
422
+ self.filename = os.path.basename(self.path)
423
+ self.shared_data = {}
424
+
425
+ self._config = workspace._config
426
+ self._workspace = workspace
427
+ self._local = local
428
+ self._source = source
429
+ self._extra_sys_path = extra_sys_path or []
430
+ self._rope_project_builder = rope_project_builder
431
+ self._lock = RLock()
432
+
433
+ jedi.settings.cache_directory = '.cache/jedi/'
434
+ jedi.settings.use_filesystem_cache = True
435
+ jedi.settings.auto_import_modules = self._get_auto_import_modules()
436
+
437
+ def _get_auto_import_modules(self):
438
+ installed_packages_list = [dist.metadata['Name'] for dist in importlib.metadata.distributions()]
439
+ auto_import_modules = [pkg for pkg in installed_packages_list if pkg not in self.DO_NOT_PRELOAD_MODULES]
440
+ return auto_import_modules
441
+
442
+ def __str__(self):
443
+ return str(self.uri)
444
+
445
+ def _rope_resource(self, rope_config):
446
+ from rope.base import libutils
447
+
448
+ return libutils.path_to_resource(
449
+ self._rope_project_builder(rope_config), self.path
450
+ )
451
+
452
+ @property
453
+ @lock
454
+ def lines(self):
455
+ return self.source.splitlines(True)
456
+
457
+ @property
458
+ @lock
459
+ def source(self):
460
+ if self._source is None:
461
+ with io.open(self.path, "r", encoding="utf-8") as f:
462
+ return f.read()
463
+ return self._source
464
+
465
+ def update_config(self, settings) -> None:
466
+ self._config.update((settings or {}).get("pylsp", {}))
467
+
468
+ @lock
469
+ def apply_change(self, change):
470
+ """Apply a change to the document."""
471
+ text = change["text"]
472
+ change_range = change.get("range")
473
+
474
+ if not change_range:
475
+ # The whole file has changed
476
+ self._source = text
477
+ return
478
+
479
+ start_line = change_range["start"]["line"]
480
+ start_col = change_range["start"]["character"]
481
+ end_line = change_range["end"]["line"]
482
+ end_col = change_range["end"]["character"]
483
+
484
+ # Check for an edit occuring at the very end of the file
485
+ if start_line == len(self.lines):
486
+ self._source = self.source + text
487
+ return
488
+
489
+ new = io.StringIO()
490
+
491
+ # Iterate over the existing document until we hit the edit range,
492
+ # at which point we write the new text, then loop until we hit
493
+ # the end of the range and continue writing.
494
+ for i, line in enumerate(self.lines):
495
+ if i < start_line:
496
+ new.write(line)
497
+ continue
498
+
499
+ if i > end_line:
500
+ new.write(line)
501
+ continue
502
+
503
+ if i == start_line:
504
+ new.write(line[:start_col])
505
+ new.write(text)
506
+
507
+ if i == end_line:
508
+ new.write(line[end_col:])
509
+
510
+ self._source = new.getvalue()
511
+
512
+ def offset_at_position(self, position):
513
+ """Return the byte-offset pointed at by the given position."""
514
+ return position["character"] + len("".join(self.lines[: position["line"]]))
515
+
516
+ def word_at_position(self, position):
517
+ """Get the word under the cursor returning the start and end positions."""
518
+ if position["line"] >= len(self.lines):
519
+ return ""
520
+
521
+ line = self.lines[position["line"]]
522
+ i = position["character"]
523
+ # Split word in two
524
+ start = line[:i]
525
+ end = line[i:]
526
+
527
+ # Take end of start and start of end to find word
528
+ # These are guaranteed to match, even if they match the empty string
529
+ m_start = RE_START_WORD.findall(start)
530
+ m_end = RE_END_WORD.findall(end)
531
+
532
+ return m_start[0] + m_end[-1]
533
+
534
+ @lock
535
+ def jedi_names(self, all_scopes=False, definitions=True, references=False):
536
+ script = self.jedi_script()
537
+ return script.get_names(
538
+ all_scopes=all_scopes, definitions=definitions, references=references
539
+ )
540
+
541
+ @lock
542
+ def jedi_script(self, position=None, use_document_path=False):
543
+ extra_paths = []
544
+ environment_path = None
545
+ env_vars = None
546
+ prioritize_extra_paths = False
547
+
548
+ if self._config:
549
+ jedi_settings = self._config.plugin_settings(
550
+ "jedi", document_path=self.path
551
+ )
552
+ jedi.settings.auto_import_modules = jedi_settings.get(
553
+ "auto_import_modules", DEFAULT_AUTO_IMPORT_MODULES
554
+ )
555
+ environment_path = jedi_settings.get("environment")
556
+ # Jedi itself cannot deal with homedir-relative paths.
557
+ # On systems, where it is expected, expand the home directory.
558
+ if environment_path and os.name != "nt":
559
+ environment_path = os.path.expanduser(environment_path)
560
+
561
+ extra_paths = jedi_settings.get("extra_paths") or []
562
+ env_vars = jedi_settings.get("env_vars")
563
+ prioritize_extra_paths = jedi_settings.get("prioritize_extra_paths")
564
+
565
+ # Drop PYTHONPATH from env_vars before creating the environment to
566
+ # ensure that Jedi can startup properly without module name collision.
567
+ if env_vars is None:
568
+ env_vars = os.environ.copy()
569
+ env_vars.pop("PYTHONPATH", None)
570
+
571
+ sys_path = self.sys_path(
572
+ environment_path, env_vars, prioritize_extra_paths, extra_paths
573
+ )
574
+
575
+ import __main__
576
+
577
+ # Extend sys_path with document's path if requested
578
+ if use_document_path:
579
+ sys_path += [os.path.normpath(os.path.dirname(self.path))]
580
+
581
+ kwargs = {
582
+ "code": self.source,
583
+ "path": self.path,
584
+ 'namespaces': [__main__.__dict__]
585
+ }
586
+
587
+ if position:
588
+ # Deprecated by Jedi to use in Script() constructor
589
+ kwargs += _utils.position_to_jedi_linecolumn(self, position)
590
+
591
+ return jedi.Interpreter(**kwargs)
592
+
593
+ def get_enviroment(self, environment_path=None, env_vars=None):
594
+ # TODO(gatesn): #339 - make better use of jedi environments, they seem pretty powerful
595
+ if environment_path is None:
596
+ environment = jedi.api.environment.get_cached_default_environment()
597
+ else:
598
+ if environment_path in self._workspace._environments:
599
+ environment = self._workspace._environments[environment_path]
600
+ else:
601
+ environment = jedi.api.environment.create_environment(
602
+ path=environment_path, safe=False, env_vars=env_vars
603
+ )
604
+ self._workspace._environments[environment_path] = environment
605
+
606
+ return environment
607
+
608
+ def sys_path(
609
+ self,
610
+ environment_path=None,
611
+ env_vars=None,
612
+ prioritize_extra_paths=False,
613
+ extra_paths=[],
614
+ ):
615
+ # Copy our extra sys path
616
+ path = list(self._extra_sys_path)
617
+ environment = self.get_enviroment(
618
+ environment_path=environment_path, env_vars=env_vars
619
+ )
620
+ path.extend(environment.get_sys_path())
621
+ if prioritize_extra_paths:
622
+ path = extra_paths + path
623
+ else:
624
+ path = path + extra_paths
625
+
626
+ return path
627
+
628
+
629
+ class Notebook:
630
+ """Represents a notebook."""
631
+
632
+ def __init__(
633
+ self, uri, notebook_type, workspace, cells=None, version=None, metadata=None
634
+ ) -> None:
635
+ self.uri = uri
636
+ self.notebook_type = notebook_type
637
+ self.workspace = workspace
638
+ self.version = version
639
+ self.cells = cells or []
640
+ self.metadata = metadata or {}
641
+ self._lock = RLock()
642
+
643
+ def __str__(self):
644
+ return "Notebook with URI '%s'" % str(self.uri)
645
+
646
+ def add_cells(self, new_cells: List, start: int) -> None:
647
+ self.cells[start:start] = new_cells
648
+
649
+ def remove_cells(self, start: int, delete_count: int) -> None:
650
+ del self.cells[start : start + delete_count]
651
+
652
+ def cell_data(self):
653
+ """Extract current cell data.
654
+
655
+ Returns a dict (ordered by cell position) where the key is the cell uri and the
656
+ value is a dict with line_start, line_end, and source attributes.
657
+ """
658
+ cell_data = {}
659
+ offset = 0
660
+ for cell in self.cells:
661
+ cell_uri = cell["document"]
662
+ cell_document = self.workspace.get_cell_document(cell_uri)
663
+ num_lines = cell_document.line_count
664
+ cell_data[cell_uri] = {
665
+ "line_start": offset,
666
+ "line_end": offset + num_lines - 1,
667
+ "source": cell_document.source,
668
+ }
669
+ offset += num_lines
670
+ return cell_data
671
+
672
+ @lock
673
+ def jedi_names(
674
+ self,
675
+ up_to_cell_uri: Optional[str] = None,
676
+ all_scopes=False,
677
+ definitions=True,
678
+ references=False,
679
+ ):
680
+ """
681
+ Get the names in the notebook up to a certain cell.
682
+
683
+ Parameters
684
+ ----------
685
+ up_to_cell_uri: str, optional
686
+ The cell uri to stop at. If None, all cells are considered.
687
+ """
688
+ names = set()
689
+ for cell in self.cells:
690
+ cell_uri = cell["document"]
691
+ cell_document = self.workspace.get_cell_document(cell_uri)
692
+ names.update(cell_document.jedi_names(all_scopes, definitions, references))
693
+ if cell_uri == up_to_cell_uri:
694
+ break
695
+ return {name.name for name in names}
696
+
697
+
698
+ class Cell(Document):
699
+ """
700
+ Represents a cell in a notebook.
701
+
702
+ Notes
703
+ -----
704
+ We inherit from Document for now to get the same API. However, a cell document differs from text documents in that
705
+ they have a language id.
706
+ """
707
+
708
+ def __init__(
709
+ self,
710
+ uri,
711
+ notebook_uri,
712
+ language_id,
713
+ workspace,
714
+ source=None,
715
+ version=None,
716
+ local=True,
717
+ extra_sys_path=None,
718
+ rope_project_builder=None,
719
+ ) -> None:
720
+ super().__init__(
721
+ uri, workspace, source, version, local, extra_sys_path, rope_project_builder
722
+ )
723
+ self.language_id = language_id
724
+ self.notebook_uri = notebook_uri
725
+
726
+ @property
727
+ @lock
728
+ def line_count(self):
729
+ """ "Return the number of lines in the cell document."""
730
+ return len(self.source.split("\n"))