Skip to content

Commit

Permalink
Add basic workspace index dataclasses
Browse files Browse the repository at this point in the history
  • Loading branch information
krukas committed Jun 12, 2024
1 parent 3fe15e4 commit b3946a4
Show file tree
Hide file tree
Showing 3 changed files with 100 additions and 11 deletions.
83 changes: 83 additions & 0 deletions djlsp/index.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
from dataclasses import dataclass, field


@dataclass
class Template:
file_path: str = ""
workspace_file_path: str = ""
context: dict = field(default_factory=dict)
# Attributes filled by parser
extends: str | None = None
loaded_libraries: list[str] | None = None
blocks: list[str] | None = None

def clear(self):
self.extends = None
self.blocks = None


@dataclass
class Tag:
name: str = ""
in_between_tags: list[str] = ""
closing_tag: str = ""


@dataclass
class Library:
name: str = ""
tags: dict[str, Tag] = field(default_factory=dict)
filters: list[str] = field(default_factory=list)


@dataclass
class WorkspaceIndex:
file_watcher_globs: [str] = field(default_factory=list)
static_files: [str] = field(default_factory=list)
urls: [str] = field(default_factory=list)
libraries: dict[str, Library] = field(default_factory=dict)
templates: dict[str, Template] = field(default_factory=dict)

def update(self, django_data: dict):
self.file_watcher_globs = django_data.get(
"file_watcher_globs", self.file_watcher_globs
)
self.static_files = django_data.get("static_files", self.static_files)
self.urls = django_data.get("urls", self.urls)

# TODO: add support in django collector
# if libraries := django_data.get("libraries"):
# self.libraries = {
# library.get("name"): Library(
# name=library.get("name"),
# filters=library.get("filters", []),
# tags={
# tag.get("name"): Tag(
# name=tag.get("name"),
# in_between_tags=tag.get("in_between_tags", []),
# closing_tag=tag.get("closing_tag"),
# )
# for tag in library.get("tags", [])
# },
# )
# for library in libraries
# }

# TODO: Add Support in django collector
# Update templates
# if templates := django_data.get("templates"):
# found_templates = []
# for template in templates:
# # TODO: how to handle template override
# file_path = template.get("file_path")
# found_templates.append(file_path)
# if file_path in self.templates:
# self.templates[file_path].context = template.get("context", dict)
# else:
# self.templates[file_path] = Template(
# file_path=file_path,
# workspace_file_path=template.get("workspace_file_path", ""),
# context=template.get("context", dict),
# )

# self.templates = [t for t in self.templates if t in found_templates]
12 changes: 8 additions & 4 deletions djlsp/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from pygls.workspace import TextDocument

from djlsp.constants import BUILTIN
from djlsp.index import WorkspaceIndex

logger = logging.getLogger(__name__)

Expand All @@ -19,7 +20,11 @@ class TemplateParser:
re_filter = re.compile(r"^.*({%|{{) ?[\w \.\|]*\|(\w*)$")
re_template = re.compile(r""".*{% ?(extends|include) ('|")([\w\-:]*)$""")

def __init__(self, django_data: dict, document: TextDocument):
def __init__(
self, workspace_index: WorkspaceIndex, django_data: dict, document: TextDocument
):
# TODO: remove use of django_data and only use workspace_index
self.workspace_index: WorkspaceIndex = workspace_index
self.django_data = django_data
self.document: TextDocument = document

Expand Down Expand Up @@ -73,7 +78,7 @@ def get_static_completions(self, match: Match):
return sorted(
[
static_file
for static_file in self.django_data["static_files"]
for static_file in self.workspace_index.static_files
if static_file.startswith(prefix)
]
)
Expand All @@ -82,13 +87,12 @@ def get_url_completions(self, match: Match):
prefix = match.group(2)
logger.debug(f"Find url matches for: {prefix}")
return sorted(
[url for url in self.django_data["urls"] if url.startswith(prefix)]
[url for url in self.workspace_index.urls if url.startswith(prefix)]
)

def get_template_completions(self, match: Match):
prefix = match.group(3)
logger.debug(f"Find {match.group(1)} matches for: {prefix}")
logger.debug(self.django_data["templates"])
return sorted(
[
template
Expand Down
16 changes: 9 additions & 7 deletions djlsp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

from djlsp import __version__
from djlsp.constants import FALLBACK_DJANGO_DATA
from djlsp.index import WorkspaceIndex
from djlsp.parser import TemplateParser

logger = logging.getLogger(__name__)
Expand All @@ -47,11 +48,12 @@ class DjangoTemplateLanguageServer(LanguageServer):
def __init__(self, *args):
super().__init__(*args)
self.file_watcher_id = str(uuid.uuid4())
self.current_file_watcher_globs = FALLBACK_DJANGO_DATA["file_watcher_globs"]
self.current_file_watcher_globs = []
self.docker_compose_file = "docker-compose.yml"
self.docker_compose_service = "django"
self.django_settings_module = ""
self.django_data = FALLBACK_DJANGO_DATA
self.workspace_index = WorkspaceIndex()

def set_initialization_options(self, options: dict):
self.docker_compose_file = options.get(
Expand Down Expand Up @@ -96,6 +98,7 @@ def get_django_data(self):
if django_data:
# TODO: Maybe validate data
self.django_data = django_data
self.workspace_index.update(django_data)
logger.info("Collected project Django data:")
logger.info(f" - Libraries: {len(django_data['libraries'])}")
logger.info(f" - Templates: {len(django_data['templates'])}")
Expand All @@ -104,10 +107,10 @@ def get_django_data(self):
else:
logger.info("Could not collect Django data")

if "file_watcher_globs" in django_data and set(
django_data["file_watcher_globs"]
) != set(self.current_file_watcher_globs):
self.current_file_watcher_globs = django_data["file_watcher_globs"]
if set(self.workspace_index.file_watcher_globs) != set(
self.current_file_watcher_globs
):
self.current_file_watcher_globs = self.workspace_index.file_watcher_globs
self.set_file_watcher_capability()

def _get_python_path(self):
Expand Down Expand Up @@ -219,7 +222,6 @@ def initialized(ls: DjangoTemplateLanguageServer, params: InitializeParams):
if params.initialization_options:
ls.set_initialization_options(params.initialization_options)
ls.get_django_data()
ls.set_file_watcher_capability()


@server.feature(
Expand All @@ -230,7 +232,7 @@ def completions(ls: DjangoTemplateLanguageServer, params: CompletionParams):
logger.debug(f"PARAMS: {params}")
items = []
document = server.workspace.get_document(params.text_document.uri)
template = TemplateParser(ls.django_data, document)
template = TemplateParser(ls.workspace_index, ls.django_data, document)
for completion in template.completions(
params.position.line, params.position.character
):
Expand Down

0 comments on commit b3946a4

Please sign in to comment.