From f2fb2b79ea20432ee1094b7817d8cf9af9e11729 Mon Sep 17 00:00:00 2001 From: l0ng-ai <24760907+l0ng-ai@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:47:53 +0800 Subject: [PATCH] feat(editor): support Helm and Go templates --- crates/ide-language/src/lib.rs | 3 + crates/ide-language/src/registry.rs | 80 ++++++++++++---- crates/ide-tools/src/lib.rs | 74 ++++++++++----- crates/ide-tools/src/registry.rs | 45 +++++++++ crates/ide-tools/src/sources.rs | 4 + fixtures/helm-chart/Chart.yaml | 4 + fixtures/helm-chart/docker-stack.yaml.tmpl | 7 ++ fixtures/helm-chart/templates/_helpers.tpl | 3 + fixtures/helm-chart/templates/configmap.yaml | 6 ++ fixtures/helm-chart/values.yaml | 1 + languages/gotmpl.toml | 12 +++ languages/helm-template.toml | 17 ++-- src/editor/core/cm/helm.test.ts | 22 ++++- src/editor/core/cm/helm.ts | 97 +++++++++++--------- src/editor/core/cm/languages.ts | 9 +- src/platform/locales/text/en.json | 2 + src/platform/locales/text/zh.json | 2 + src/ui/icons.test.tsx | 8 +- src/ui/icons.tsx | 4 +- 19 files changed, 299 insertions(+), 101 deletions(-) create mode 100644 fixtures/helm-chart/Chart.yaml create mode 100644 fixtures/helm-chart/docker-stack.yaml.tmpl create mode 100644 fixtures/helm-chart/templates/_helpers.tpl create mode 100644 fixtures/helm-chart/templates/configmap.yaml create mode 100644 fixtures/helm-chart/values.yaml create mode 100644 languages/gotmpl.toml diff --git a/crates/ide-language/src/lib.rs b/crates/ide-language/src/lib.rs index cff6bce301..2e7127e5e9 100644 --- a/crates/ide-language/src/lib.rs +++ b/crates/ide-language/src/lib.rs @@ -121,6 +121,9 @@ pub struct FrameworkFiles { pub extensions: Vec, /// Matched like language servers' `root-markers`, e.g. `manage.py`. pub root_markers: Vec, + /// Require the marker directly beside `folder`. + #[serde(default)] + pub root_marker_in_parent: bool, } #[derive(Clone, Copy, Debug, Serialize, Deserialize, Type)] diff --git a/crates/ide-language/src/registry.rs b/crates/ide-language/src/registry.rs index 6bb321416f..aec620d072 100644 --- a/crates/ide-language/src/registry.rs +++ b/crates/ide-language/src/registry.rs @@ -33,6 +33,7 @@ const BUILTIN: &[(&str, &str)] = &[ ("gdscript", include_str!("../../../languages/gdscript.toml")), ("gdshader", include_str!("../../../languages/gdshader.toml")), ("go", include_str!("../../../languages/go.toml")), + ("gotmpl", include_str!("../../../languages/gotmpl.toml")), ("gherkin", include_str!("../../../languages/gherkin.toml")), ("gomod", include_str!("../../../languages/gomod.toml")), ("gowork", include_str!("../../../languages/gowork.toml")), @@ -406,7 +407,14 @@ impl LanguageRegistry { if let Some((_, i)) = t.name_globs.iter().find(|(p, _)| wildcard_match(p, file_name)) { return languages[*i].id.clone(); } - if let Some(l) = languages.iter().find(|l| l.framework_files.iter().any(|f| is_framework_file(f, path))) { + let framework_language = |root_marker_in_parent| { + languages.iter().find(|l| { + l.framework_files + .iter() + .any(|f| f.root_marker_in_parent == root_marker_in_parent && is_framework_file(f, path)) + }) + }; + if let Some(l) = framework_language(true).or_else(|| framework_language(false)) { return l.id.clone(); } let lower = file_name.to_ascii_lowercase(); @@ -429,17 +437,21 @@ impl LanguageRegistry { } } -/// `path` is one of `files`: its extension is listed, and the nearest folder above it named -/// `files.folder` has a root marker in a directory above that folder. +/// `path` has a listed extension and lies under a matching folder with a root marker. fn is_framework_file(files: &crate::FrameworkFiles, path: &Path) -> bool { let Some(ext) = path.extension().and_then(|e| e.to_str()) else { return false }; if !files.extensions.iter().any(|e| e.eq_ignore_ascii_case(ext)) { return false; } - path.ancestors() - .skip(1) - .find(|dir| dir.file_name().is_some_and(|name| name == files.folder.as_str())) - .is_some_and(|folder| crate::marked_root(None, folder, &files.root_markers).is_some()) + let mut folders = + path.ancestors().skip(1).filter(|dir| dir.file_name().is_some_and(|name| name == files.folder.as_str())); + if files.root_marker_in_parent { + folders + .filter_map(Path::parent) + .any(|parent| crate::marked_root(Some(parent), parent, &files.root_markers).is_some()) + } else { + folders.next().is_some_and(|folder| crate::marked_root(None, folder, &files.root_markers).is_some()) + } } /// `*` matches any (possibly empty) run of characters, `?` exactly one; everything else is literal. @@ -486,6 +498,7 @@ mod tests { "CQL", "CSS", "Go", + "Go Template", "HTML", "Java", "JavaScript", @@ -997,21 +1010,52 @@ mod tests { std::fs::create_dir_all(root.join("charts/podinfo/templates/tests")).unwrap(); std::fs::create_dir_all(root.join("k8s/templates")).unwrap(); std::fs::write(root.join("charts/podinfo/Chart.yaml"), "apiVersion: v2\nname: podinfo\n").unwrap(); - assert_eq!(detect("charts/podinfo/Chart.yaml"), "yaml"); - assert_eq!(detect("charts/podinfo/values.yaml"), "yaml"); - assert_eq!(detect("charts/podinfo/templates/deployment.yaml"), "helm-template"); - assert_eq!(detect("charts/podinfo/templates/tests/connection.yml"), "helm-template"); - assert_eq!(detect("charts/podinfo/templates/_helpers.tpl"), "helm-template"); - assert_eq!(detect("charts/podinfo/templates/NOTES.txt"), "helm-template"); - // No `Chart.yaml` / `Chart.yml` above this `templates` folder. - assert_eq!(detect("k8s/templates/deployment.yaml"), "yaml"); - assert_eq!(detect("common.gotmpl"), "helm-template"); - // Outside a chart, `.tpl` belongs to other template engines (Smarty, Terraform). - assert_ne!(detect("site/index.tpl"), "helm-template"); + std::fs::write(root.join("manage.py"), "").unwrap(); + for file in [ + "deployment.yaml", + "tests/connection.yml", + "_helpers.tpl", + "NOTES.txt", + "dashboard.json", + "config.yaml.gotmpl", + "config.yaml.go.tmpl", + "tests/templates/check.YAML", + ] { + let path = format!("charts/podinfo/templates/{file}"); + assert_eq!(detect(&path), "helm-template", "{path}"); + } + for (path, language) in [ + ("charts/podinfo/Chart.yaml", "yaml"), + ("charts/podinfo/values.yaml", "yaml"), + ("charts/podinfo/docs/templates/deployment.yaml", "yaml"), + ("charts/podinfo/docs/templates/_helpers.tpl", "plaintext"), + ("charts/podinfo/docs/templates/sample.tmpl", "gotmpl"), + ("charts/podinfo/docs/templates/notes.txt", "django-html"), + ("k8s/templates/deployment.yaml", "yaml"), + ("site/index.tpl", "plaintext"), + ] { + assert_eq!(detect(path), language, "{path}"); + } assert!(reg.is_framework_marker(&root.join("charts/podinfo/Chart.yaml"))); assert!(reg.is_framework_marker(&root.join("charts/podinfo/Chart.yml"))); } + #[test] + fn standalone_go_templates_are_detected_by_extension() { + let reg = reg(); + for (path, language) in [ + ("common.gotmpl", "gotmpl"), + ("email.tmpl", "gotmpl"), + ("config.go.tmpl", "gotmpl"), + ("config.GO.TMPL", "gotmpl"), + ("docker-stack.yaml.tmpl", "gotmpl"), + ("docker-stack.yaml", "yaml"), + ("main.go", "go"), + ] { + assert_eq!(reg.detect(Path::new(path), None).as_str(), language, "{path}"); + } + } + #[test] fn the_django_fixture_has_templates_and_a_page() { let reg = reg(); diff --git a/crates/ide-tools/src/lib.rs b/crates/ide-tools/src/lib.rs index ea226d1c9d..3707e6e47c 100644 --- a/crates/ide-tools/src/lib.rs +++ b/crates/ide-tools/src/lib.rs @@ -1439,26 +1439,10 @@ impl Tools { sha256: Some(sha256.into()), checksum_url: None, }), - ReleaseSource::GitHub { repo } => match http.get_text(&sources::github_latest_url(repo), cancel) { - Ok(json) => sources::github_pick(&json, assets, self.platform), - Err(e) if e.kind == ErrorKind::Cancelled => Err(e), - // Without a token the API allows 60 requests an hour per IP address, often used - // up behind a shared one (403/429); the release's web pages have no such limit. - Err(api) => self.resolve_github_web(http, repo, assets, cancel).map_err(|web| { - if web.kind == ErrorKind::Cancelled { - return web; - } - tracing::warn!("GitHub release lookup for {repo} failed: {api}; web pages: {web}"); - IdeError::new( - api.kind, - format!( - "{}\nDownload it from {} and set its Path in Settings › Languages & Frameworks › Language Servers.", - api.message, - sources::github_latest_page(repo) - ), - ) - }), - }, + ReleaseSource::GitHub { repo } => self.resolve_github_release(http, repo, None, assets, cancel), + ReleaseSource::GitHubTag { repo, tag } => { + self.resolve_github_release(http, repo, Some(tag), assets, cancel) + } ReleaseSource::HashiCorp { product } => { let json = http.get_text(&sources::hashicorp_latest_url(product), cancel)?; sources::hashicorp_pick(&json, assets, self.platform) @@ -1485,17 +1469,53 @@ impl Tools { } } - /// [`resolve_release`](Self::resolve_release) for a GitHub release, from its web pages. + fn resolve_github_release( + &self, + http: &Http, + repo: &str, + tag: Option<&str>, + assets: &[platform::AssetRule], + cancel: &CancellationToken, + ) -> IdeResult { + let api_url = tag.map_or_else(|| sources::github_latest_url(repo), |tag| sources::github_tag_url(repo, tag)); + match http.get_text(&api_url, cancel) { + Ok(json) => sources::github_pick(&json, assets, self.platform), + Err(e) if e.kind == ErrorKind::Cancelled => Err(e), + // Shared IP addresses can run out of unauthenticated API requests (403/429). + Err(api) => self.resolve_github_web(http, repo, tag, assets, cancel).map_err(|web| { + if web.kind == ErrorKind::Cancelled { + return web; + } + let page = tag.map_or_else(|| sources::github_latest_page(repo), |tag| sources::github_tag_page(repo, tag)); + tracing::warn!("GitHub release lookup for {repo} failed: {api}; web pages: {web}"); + IdeError::new( + api.kind, + format!( + "{}\nDownload it from {page} and set its Path in Settings › Languages & Frameworks › Language Servers.", + api.message + ), + ) + }), + } + } + + /// Resolve a GitHub release from its web pages when the API is unavailable. fn resolve_github_web( &self, http: &Http, repo: &str, + tag: Option<&str>, assets: &[platform::AssetRule], cancel: &CancellationToken, ) -> IdeResult { - let page = http.effective_url(&sources::github_latest_page(repo), cancel)?; - let tag = sources::github_tag_from_url(&page) - .ok_or_else(|| IdeError::unavailable(format!("{repo} has no published release")))?; + let tag = match tag { + Some(tag) => tag.to_owned(), + None => { + let page = http.effective_url(&sources::github_latest_page(repo), cancel)?; + sources::github_tag_from_url(&page) + .ok_or_else(|| IdeError::unavailable(format!("{repo} has no published release")))? + } + }; let list = http.get_text(&sources::github_assets_page(repo, &tag), cancel)?; match sources::github_pick_web(repo, &tag, &list, None, assets, self.platform) { Err(e) if e.kind == ErrorKind::Unavailable => { @@ -1516,7 +1536,11 @@ impl Tools { emit: Emit, ) -> IdeResult<()> { let http = Http::new(&self.system_path)?; - emit(InstallEvent::Line { text: "Resolving the latest release…".into() }); + let message = match source { + ReleaseSource::GitHubTag { tag, .. } => format!("Resolving release {tag}…"), + _ => "Resolving the latest release…".into(), + }; + emit(InstallEvent::Line { text: message }); let dl = self.resolve_release(&http, source, assets, cancel)?; emit(InstallEvent::Line { text: format!("Downloading {} ({})", dl.name, dl.url) }); let staging = self.root.join(format!(".staging-{}", spec.name)); diff --git a/crates/ide-tools/src/registry.rs b/crates/ide-tools/src/registry.rs index 7f60c8a0b7..aa117f1942 100644 --- a/crates/ide-tools/src/registry.rs +++ b/crates/ide-tools/src/registry.rs @@ -24,6 +24,8 @@ pub enum ReleaseSource { Fixed { version: &'static str, url: &'static str, sha256: &'static str }, /// Latest GitHub release of `owner/repo`; assets plus links in the release notes. GitHub { repo: &'static str }, + /// Assets from a specific GitHub release tag. + GitHubTag { repo: &'static str, tag: &'static str }, /// `api.releases.hashicorp.com` product. HashiCorp { product: &'static str }, /// Latest Eclipse JDT LS milestone tarball from download.eclipse.org. @@ -604,6 +606,27 @@ pub static TOOLS: &[ToolSpec] = &[ homepage: "https://github.com/samehelhawary/phoxite", needs: &[], }, + ToolSpec { + name: "helm-ls", + display: "helm-ls", + kind: LanguageServer, + commands: &["helm_ls"], + method: Method::Release { + source: ReleaseSource::GitHubTag { repo: "mrjosh/helm-ls", tag: "v0.5.4" }, + assets: &[ + rule(Mac, Arm64, "helm_ls_darwin_arm64"), + rule(Mac, X64, "helm_ls_darwin_amd64"), + rule(Linux, Arm64, "helm_ls_linux_arm64"), + rule(Linux, X64, "helm_ls_linux_amd64"), + rule(Windows, X64, "helm_ls_windows_amd64.exe"), + ], + locate: &["helm_ls"], + }, + fallback: None, + version: Some(("helm_ls", &["version"])), + homepage: "https://github.com/mrjosh/helm-ls", + needs: &[], + }, ToolSpec { name: "gopls", display: "gopls", @@ -1362,6 +1385,28 @@ mod tests { } } + #[test] + fn helm_ls_picks_the_pinned_native_binary() { + use crate::platform::{Platform, select_asset}; + let spec = find("helm-ls").unwrap(); + assert!(matches!( + spec.method, + Method::Release { source: ReleaseSource::GitHubTag { repo: "mrjosh/helm-ls", tag: "v0.5.4" }, .. } + )); + let releases = [ + (Mac, Arm64, "helm_ls_darwin_arm64"), + (Mac, X64, "helm_ls_darwin_amd64"), + (Linux, Arm64, "helm_ls_linux_arm64"), + (Linux, X64, "helm_ls_linux_amd64"), + (Windows, X64, "helm_ls_windows_amd64.exe"), + ]; + let checksums = releases.map(|(_, _, name)| format!("{name}.sha256sum")); + let names: Vec<_> = checksums.iter().map(String::as_str).chain(releases.map(|(_, _, name)| name)).collect(); + for (os, arch, name) in releases { + assert_eq!(select_asset(&names, spec.asset_rules(), Platform { os, arch }), Some(name)); + } + } + /// The v263 kotlin-server-* release notes: the CLI distribution archives plus /// the VS Code extension and checksums; each platform must pick its native /// distribution and the aarch64 archive must never be picked on x64. diff --git a/crates/ide-tools/src/sources.rs b/crates/ide-tools/src/sources.rs index 0e5da74811..54536347f4 100644 --- a/crates/ide-tools/src/sources.rs +++ b/crates/ide-tools/src/sources.rs @@ -47,6 +47,10 @@ pub fn github_latest_url(repo: &str) -> String { format!("https://api.github.com/repos/{repo}/releases/latest") } +pub fn github_tag_url(repo: &str, tag: &str) -> String { + format!("https://api.github.com/repos/{repo}/releases/tags/{tag}") +} + /// The latest release's web page; it redirects to `…/releases/tag/`. Web pages don't /// count against the API's rate limit for unauthenticated clients (60 requests an hour). pub fn github_latest_page(repo: &str) -> String { diff --git a/fixtures/helm-chart/Chart.yaml b/fixtures/helm-chart/Chart.yaml new file mode 100644 index 0000000000..2554cc4949 --- /dev/null +++ b/fixtures/helm-chart/Chart.yaml @@ -0,0 +1,4 @@ +apiVersion: v2 +name: hello +description: A sample chart for template editing +version: 0.1.0 diff --git a/fixtures/helm-chart/docker-stack.yaml.tmpl b/fixtures/helm-chart/docker-stack.yaml.tmpl new file mode 100644 index 0000000000..e99356db60 --- /dev/null +++ b/fixtures/helm-chart/docker-stack.yaml.tmpl @@ -0,0 +1,7 @@ +services: + web: + image: {{ printf "nginx:%s" .Tag }} + {{- if .Replicas }} + deploy: + replicas: {{ .Replicas }} + {{- end }} diff --git a/fixtures/helm-chart/templates/_helpers.tpl b/fixtures/helm-chart/templates/_helpers.tpl new file mode 100644 index 0000000000..1d762758b0 --- /dev/null +++ b/fixtures/helm-chart/templates/_helpers.tpl @@ -0,0 +1,3 @@ +{{- define "hello.name" -}} +{{ .Release.Name }} +{{- end -}} diff --git a/fixtures/helm-chart/templates/configmap.yaml b/fixtures/helm-chart/templates/configmap.yaml new file mode 100644 index 0000000000..e8c1681803 --- /dev/null +++ b/fixtures/helm-chart/templates/configmap.yaml @@ -0,0 +1,6 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "hello.name" . }} +data: + message: {{ .Values.message | quote }} diff --git a/fixtures/helm-chart/values.yaml b/fixtures/helm-chart/values.yaml new file mode 100644 index 0000000000..2043c1cca1 --- /dev/null +++ b/fixtures/helm-chart/values.yaml @@ -0,0 +1 @@ +message: Hello from Helm diff --git a/languages/gotmpl.toml b/languages/gotmpl.toml new file mode 100644 index 0000000000..bcfefedfcb --- /dev/null +++ b/languages/gotmpl.toml @@ -0,0 +1,12 @@ +id = "gotmpl" +name = "Go Template" +extensions = ["gotmpl", "tmpl"] +block-comment = ["{{/*", "*/}}"] +ui-mode = "Go Template" + +[[language-servers]] +name = "gopls" +command = "gopls" +initialization-options = { semanticTokens = true, vulncheck = "Imports", hints = { constantValues = true } } +root-markers = ["go.work", "go.mod"] +install-hint = "go install golang.org/x/tools/gopls@latest" diff --git a/languages/helm-template.toml b/languages/helm-template.toml index c4a6a3846e..027e29d339 100644 --- a/languages/helm-template.toml +++ b/languages/helm-template.toml @@ -1,16 +1,21 @@ id = "helm-template" name = "Helm Template" -# `.tpl` is Smarty, Terraform and other template engines too: only charts claim it (below). -extensions = ["gotmpl"] line-comment = "#" block-comment = ["{{/*", "*/}}"] indent = { tab-size = 2, insert-spaces = true } ui-mode = "Helm Template" -# Helm charts: YAML, template and notes files in a `templates` folder. -# No YAML formatter or strict YAML language server: Go `{{ … }}` actions are -# not valid YAML until rendered by `helm template`. +# Helm charts: YAML, templates and notes in the chart's `templates` folder. [[framework-files]] folder = "templates" -extensions = ["yaml", "yml", "tpl", "txt"] +extensions = ["yaml", "yml", "json", "tpl", "txt", "gotmpl", "tmpl"] root-markers = ["Chart.yaml", "Chart.yml"] +root-marker-in-parent = true + +[[language-servers]] +name = "helm-ls" +command = "helm_ls" +args = ["serve"] +root-markers = ["Chart.yaml"] +require-root-marker = true +install-hint = "https://github.com/mrjosh/helm-ls/releases/tag/v0.5.4" diff --git a/src/editor/core/cm/helm.test.ts b/src/editor/core/cm/helm.test.ts index f4b6a03945..52d6d91c8d 100644 --- a/src/editor/core/cm/helm.test.ts +++ b/src/editor/core/cm/helm.test.ts @@ -4,8 +4,8 @@ import { completedSyntaxTree } from "@/test/syntax"; import { classHighlighter, highlightTree } from "@lezer/highlight"; import { findLanguageDescription, loadSupport } from "./languages"; -async function tokens(source: string) { - const desc = findLanguageDescription("Helm Template", "templates/applications.yaml")!; +async function tokens(source: string, mode = "Helm Template") { + const desc = findLanguageDescription(mode, "")!; const support = await loadSupport(desc); const state = EditorState.create({ doc: source, extensions: [support!] }); const result: { text: string; style: string }[] = []; @@ -52,3 +52,21 @@ describe("Helm Template mode", () => { expect(out).toContainEqual(expect.objectContaining({ text: "replicas", style: "tok-propertyName" })); }); }); + +describe("Go Template mode", () => { + it.each(["common.gotmpl", "message.tmpl", "docker-stack.yaml.go.tmpl"])("loads for %s", (path) => { + expect(findLanguageDescription(null, path)?.name).toBe("Go Template"); + }); + + it("highlights actions and keeps host text plain", async () => { + const out = await tokens( + 'services:\n web: {{- if .Image }}{{ printf "nginx:%s" .Image }}{{ end -}}\n{{/* note */}}', + "Go Template", + ); + expect(out).toContainEqual({ text: "if", style: "tok-keyword" }); + expect(out).toContainEqual({ text: ".Image", style: "tok-propertyName" }); + expect(out).toContainEqual({ text: '"nginx:%s"', style: "tok-string" }); + expect(out.some(({ text }) => /services|web/.test(text))).toBe(false); + expect(out).toContainEqual({ text: "{{/* note */}}", style: "tok-comment" }); + }); +}); diff --git a/src/editor/core/cm/helm.ts b/src/editor/core/cm/helm.ts index 67ed365010..09a2d20d91 100644 --- a/src/editor/core/cm/helm.ts +++ b/src/editor/core/cm/helm.ts @@ -1,16 +1,14 @@ -// Helm Template editor mode: YAML outside `{{ … }}`, Go `text/template` + Sprig/Helm -// actions and `{{/* … */}}` comments inside. Each region runs on a sub-stream bounded -// at the next delimiter so `{{ … }}` never breaks YAML key/value tokenization. +// Go text/template actions over plain text or Helm YAML. The YAML parser reads up to the +// next template delimiter so the action never breaks YAML key/value tokenization. import { LanguageSupport, StreamLanguage, StringStream, type StreamParser } from "@codemirror/language"; import { tags } from "@lezer/highlight"; -type HelmState = { +type TemplateState = { yaml: Y; inAction: boolean; inComment: boolean; inRawString: boolean; quote: '"' | "'" | null; - indentUnit: number; }; const OPEN = /\{\{-?/; @@ -21,56 +19,60 @@ const COMMENT_CLOSE = /\*\/\s*-?\}\}/; const KEYWORDS = new Set(["if", "else", "end", "range", "with", "define", "template", "block", "break", "continue"]); const ATOMS = new Set(["true", "false", "nil"]); -const FUNCTIONS = new Set([ +const BUILTINS = new Set([ "and", + "call", + "eq", + "ge", + "gt", + "html", + "index", + "js", + "le", + "len", + "lt", + "ne", + "not", + "or", + "print", + "printf", + "println", + "slice", + "urlquery", +]); +const HELM_FUNCTIONS = new Set([ "b64dec", "b64enc", - "call", "coalesce", "contains", "default", "dict", "empty", - "eq", "fail", "first", "fromJson", "fromYaml", - "ge", "get", - "gt", "has", "hasKey", "hasPrefix", "hasSuffix", - "html", "include", "indent", - "index", "int", "int64", "join", - "js", "keys", "kindIs", "kindOf", "last", - "le", - "len", "list", "lookup", "lower", - "lt", "merge", "mustMerge", - "ne", "nindent", - "not", - "or", "pluck", - "print", - "printf", - "println", "quote", "regexMatch", "replace", @@ -78,7 +80,6 @@ const FUNCTIONS = new Set([ "semverCompare", "set", "sha256sum", - "slice", "snakecase", "squote", "ternary", @@ -99,11 +100,10 @@ const FUNCTIONS = new Set([ "typeOf", "unset", "upper", - "urlquery", "values", ]); -function tokenAction(stream: StringStream, state: HelmState): string | null { +function tokenAction(stream: StringStream, state: TemplateState, helm: boolean): string | null { if (state.inRawString) { const end = stream.string.indexOf("`", stream.pos); if (end < 0) { @@ -122,14 +122,14 @@ function tokenAction(stream: StringStream, state: HelmState): string | nul if (close?.index === 0) { stream.pos += close[0].length; state.inAction = false; - return "helmDelimiter"; + return "templateDelimiter"; } const ch = stream.peek(); if (ch === "`") { stream.next(); state.inRawString = true; - return tokenAction(stream, state); + return tokenAction(stream, state, helm); } if (ch === '"') { stream.match(/^"(?:[^"\\]|\\.)*"?/); @@ -158,7 +158,7 @@ function tokenAction(stream: StringStream, state: HelmState): string | nul const word = stream.current(); if (KEYWORDS.has(word)) return "keyword"; if (ATOMS.has(word)) return "bool"; - if (FUNCTIONS.has(word)) return "helmFunc"; + if (BUILTINS.has(word) || (helm && HELM_FUNCTIONS.has(word))) return "templateFunc"; return "variableName"; } @@ -166,7 +166,8 @@ function tokenAction(stream: StringStream, state: HelmState): string | nul return null; } -export function helmParser(yaml: StreamParser): StreamParser> { +function templateParser(yaml?: StreamParser): StreamParser> { + const helm = yaml !== undefined; const copy = (base: StreamParser, state: Y): Y => base.copyState ? base.copyState(state) @@ -174,7 +175,11 @@ export function helmParser(yaml: StreamParser): StreamParser> Object.entries(state as object).map(([k, v]) => [k, Array.isArray(v) ? v.slice() : v]), ) as Y); - const withinYaml = (stream: StringStream, end: number, state: HelmState): string | null => { + const tokenHost = (stream: StringStream, end: number, state: TemplateState): string | null => { + if (!yaml || state.yaml === undefined) { + stream.pos = end; + return null; + } if (state.quote) { const q = state.quote; while (stream.pos < end) { @@ -220,30 +225,30 @@ export function helmParser(yaml: StreamParser): StreamParser> return style; }; + const block = { open: "{{/*", close: "*/}}" }; return { - name: "helm-template", + name: helm ? "helm-template" : "gotmpl", languageData: { - ...yaml.languageData, - commentTokens: { line: "#", block: { open: "{{/*", close: "*/}}" } }, + ...yaml?.languageData, + commentTokens: helm ? { line: "#", block } : { block }, }, tokenTable: { - ...yaml.tokenTable, + ...yaml?.tokenTable, atom: tags.propertyName, - helmDelimiter: tags.special(tags.brace), - helmFunc: tags.function(tags.variableName), + templateDelimiter: tags.special(tags.brace), + templateFunc: tags.function(tags.variableName), }, startState: (indentUnit) => ({ - yaml: yaml.startState!(indentUnit), + yaml: yaml?.startState?.(indentUnit), inAction: false, inComment: false, inRawString: false, quote: null, - indentUnit, }), - copyState: (s) => ({ ...s, yaml: copy(yaml, s.yaml) }), + copyState: (s) => ({ ...s, yaml: yaml && s.yaml !== undefined ? copy(yaml, s.yaml) : s.yaml }), blankLine: (s, unit) => { s.quote = null; - yaml.blankLine?.(s.yaml, unit); + if (yaml && s.yaml !== undefined) yaml.blankLine?.(s.yaml, unit); }, token(stream, state) { if (stream.sol()) state.quote = null; @@ -261,7 +266,7 @@ export function helmParser(yaml: StreamParser): StreamParser> } if (state.inAction) { - return tokenAction(stream, state); + return tokenAction(stream, state, helm); } const rest = stream.string.slice(stream.pos); @@ -281,16 +286,20 @@ export function helmParser(yaml: StreamParser): StreamParser> } stream.pos += open[0].length; state.inAction = true; - return "helmDelimiter"; + return "templateDelimiter"; } const end = open ? stream.pos + open.index : stream.string.length; - return withinYaml(stream, end, state); + return tokenHost(stream, end, state); }, }; } export async function helmTemplate(): Promise { const { yaml } = await import("@codemirror/legacy-modes/mode/yaml"); - return new LanguageSupport(StreamLanguage.define(helmParser(yaml))); + return new LanguageSupport(StreamLanguage.define(templateParser(yaml))); +} + +export function goTemplate(): LanguageSupport { + return new LanguageSupport(StreamLanguage.define(templateParser())); } diff --git a/src/editor/core/cm/languages.ts b/src/editor/core/cm/languages.ts index 3da9923b9e..c5a23d7a6d 100644 --- a/src/editor/core/cm/languages.ts +++ b/src/editor/core/cm/languages.ts @@ -248,10 +248,15 @@ const OWN_MODES = [ extensions: ["djhtml"], load: () => import("./django").then((m) => m.django()), }), + LanguageDescription.of({ + name: "Go Template", + alias: ["gotmpl", "tmpl"], + extensions: ["gotmpl", "tmpl"], + load: () => import("./helm").then((m) => m.goTemplate()), + }), LanguageDescription.of({ name: "Helm Template", - alias: ["helm-template", "gotmpl"], - extensions: ["gotmpl"], + alias: ["helm-template"], load: () => import("./helm").then((m) => m.helmTemplate()), }), LanguageDescription.of({ diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 6a4a9ad2b5..8c43d8407c 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -934,6 +934,8 @@ "Shell": "Shell", "C/C++": "C/C++", "Go": "Go", + "Go Template": "Go Template", + "Helm Template": "Helm Template", "Rust": "Rust", "Python": "Python", "JavaScript": "JavaScript", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 0de02237ae..53727ccef0 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -737,6 +737,8 @@ "Shell": "Shell", "C/C++": "C/C++", "Go": "Go", + "Go Template": "Go 模板", + "Helm Template": "Helm 模板", "Rust": "Rust", "Python": "Python", "JavaScript": "JavaScript", diff --git a/src/ui/icons.test.tsx b/src/ui/icons.test.tsx index 1504e622ae..bd6e51b66e 100644 --- a/src/ui/icons.test.tsx +++ b/src/ui/icons.test.tsx @@ -196,6 +196,9 @@ describe("fileIconName", () => { ["schema.graphql", "file-graphql"], ["api.proto", "file-proto"], ["main.go", "file-go"], + ["page.gotmpl", "file-go"], + ["message.tmpl", "file-go"], + ["docker-stack.yaml.go.tmpl", "file-go"], ["main.c", "file-c"], ["util.h", "file-h"], ["util.hpp", "file-h"], @@ -254,7 +257,7 @@ describe("fileIconName", () => { expect(fileIconName(file)).toBe(icon); }); - it("gives every detected language file a specific icon", () => { + it("gives every built-in filename and extension association a specific icon", () => { const dir = path.join(process.cwd(), "languages"); const list = (src: string, key: string) => [...(new RegExp(`^${key}\\s*=\\s*\\[([^\\]]*)\\]`, "m").exec(src)?.[1] ?? "").matchAll(/"([^"]+)"/g)].map( @@ -264,7 +267,8 @@ describe("fileIconName", () => { const misses: string[] = []; for (const file of fs.readdirSync(dir).filter((f) => f.endsWith(".toml"))) { if (file === "plaintext.toml") continue; - const src = fs.readFileSync(path.join(dir, file), "utf8"); + // Framework tables describe associations that require project context. + const src = fs.readFileSync(path.join(dir, file), "utf8").split(/^\[/m, 1)[0]!; const names = [ ...list(src, "extensions").map((e) => `name.${e}`), ...list(src, "filenames").map((n) => n.replace("*", "x")), diff --git a/src/ui/icons.tsx b/src/ui/icons.tsx index a1f77d020e..cd9aff574c 100644 --- a/src/ui/icons.tsx +++ b/src/ui/icons.tsx @@ -1141,7 +1141,7 @@ const EXT_ICONS = table({ "file-word": "doc docx rtf odt", "file-pdf": "pdf", "file-rst": "rst", - "file-yaml": "yaml yml gotmpl", + "file-yaml": "yaml yml", "file-toml": "toml", "file-text": "txt text", "file-log": "log", @@ -1188,7 +1188,7 @@ const EXT_ICONS = table({ "file-csharp": "cs csx", "file-fsharp": "fs fsi fsx", "file-swift": "swift swiftinterface", - "file-go": "go", + "file-go": "go gotmpl tmpl", "file-rust": "rs", "file-ruby": "rb rake gemspec ru rbi jbuilder podspec erb rhtml", "file-lua": "lua luau rockspec",