From 7f161344653dca852f83d334274fcb58ec3e74c1 Mon Sep 17 00:00:00 2001 From: Jack Cherng Date: Sat, 22 Jun 2024 16:27:17 +0800 Subject: [PATCH] refactor: allow optional `extra_variables` for update_status_bar_text() Signed-off-by: Jack Cherng --- plugin/client.py | 20 +++++++++++--------- plugin/template.py | 12 ++++++++---- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/plugin/client.py b/plugin/client.py index 88f7cd3..801633a 100644 --- a/plugin/client.py +++ b/plugin/client.py @@ -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 @@ -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) diff --git a/plugin/template.py b/plugin/template.py index 7ebfff6..aed0f8a 100644 --- a/plugin/template.py +++ b/plugin/template.py @@ -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=[ @@ -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)