Skip to content

Commit

Permalink
refactor: allow optional extra_variables for update_status_bar_text()
Browse files Browse the repository at this point in the history
Signed-off-by: Jack Cherng <jfcherng@gmail.com>
  • Loading branch information
jfcherng committed Jun 22, 2024
1 parent 01b95c9 commit 7f16134
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 13 deletions.
20 changes: 11 additions & 9 deletions plugin/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

from .constants import PACKAGE_NAME
from .log import log_info, log_warning
from .template import render_template
from .template import load_string_template
from .venv_finder import VenvInfo, find_venv_by_finder_names, get_finder_name_mapping

WindowId = int
Expand Down Expand Up @@ -140,27 +140,29 @@ def copy_overwrite_dirs(cls) -> None:
except OSError:
raise RuntimeError(f'Failed to copy overwrite dirs from "{dir_src}" to "{dir_dst}".')

def update_status_bar_text(self) -> None:
def update_status_bar_text(self, extra_variables: dict[str, Any] | None = None) -> None:
if not (session := self.weaksession()):
return
window_id = session.window.id()

variables: dict[str, Any] = {
"server_version": self.server_version,
"venv": {},
}

if venv_info := self.window_attrs[window_id].venv_info:
variables["venv"].update(
finder_name=venv_info.meta.finder_name,
python_version=venv_info.python_version,
venv_prompt=venv_info.prompt,
)
variables["venv"] = {
"finder_name": venv_info.meta.finder_name,
"python_version": venv_info.python_version,
"venv_prompt": venv_info.prompt,
}

if extra_variables:
variables.update(extra_variables)

rendered_text = ""
if template_text := str(session.config.settings.get("statusText") or ""):
try:
rendered_text = render_template(template_text, variables)
rendered_text = load_string_template(template_text).render(variables)
except Exception as e:
log_warning(f'Invalid "statusText" template: {e}')
session.set_config_status_async(rendered_text)
Expand Down
12 changes: 8 additions & 4 deletions plugin/template.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from __future__ import annotations

from functools import lru_cache
from typing import Any

import jinja2
import sublime

from .constants import PACKAGE_NAME

JINJA_TEMPLATE_ENV = jinja2.Environment(
extensions=[
Expand All @@ -14,9 +16,11 @@


@lru_cache
def create_template(template: str) -> jinja2.Template:
def load_string_template(template: str) -> jinja2.Template:
return JINJA_TEMPLATE_ENV.from_string(template)


def render_template(template: str, variables: dict[str, Any]) -> str:
return create_template(template).render(variables)
@lru_cache
def load_resource_template(resource_name: str) -> jinja2.Template:
content = sublime.load_resource(f"Packages/{PACKAGE_NAME}/plugin/templates/{resource_name}")
return load_string_template(content)

0 comments on commit 7f16134

Please sign in to comment.