diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..0574c9c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,106 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + +env: + ZED_EXTENSION_CLI_SHA: 9ee3c503a4bbbc6b4a0f8a789acca4871d773223 + +jobs: + rust: + name: Rust tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + targets: wasm32-wasip1 + - name: Unit tests + run: cargo test + - name: WASM build + run: cargo build --target wasm32-wasip1 --release + + grammar-pin: + name: Grammar pin + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "22" + - name: Install tree-sitter CLI + run: npm install -g tree-sitter-cli@0.25.10 + - name: Check pin lock and generated files + run: bash scripts/check-grammar-pin.sh + + zed-query-load: + name: Zed query load + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "22" + - name: Install tree-sitter CLI + run: npm install -g tree-sitter-cli@0.25.10 + - name: Reject queries Zed cannot register + run: bash scripts/check-zed-queries.sh + + queries: + name: Chart fixtures and queries + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "22" + - name: Install tree-sitter CLI + run: npm install -g tree-sitter-cli@0.25.10 + - name: Parse fixtures and check queries + run: bash scripts/check-queries.sh + + package: + name: Package extension + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + targets: wasm32-wasip1, wasm32-wasip2 + - id: cache-zed-extension-cli + name: Cache zed-extension CLI + uses: actions/cache@v4 + with: + path: zed-extension + key: zed-extension-${{ env.ZED_EXTENSION_CLI_SHA }} + - name: Download zed-extension CLI + if: steps.cache-zed-extension-cli.outputs.cache-hit != 'true' + run: | + wget --quiet "https://zed-extension-cli.nyc3.digitaloceanspaces.com/${ZED_EXTENSION_CLI_SHA}/x86_64-unknown-linux-gnu/zed-extension" -O "$GITHUB_WORKSPACE/zed-extension" + chmod +x "$GITHUB_WORKSPACE/zed-extension" + - name: Package with zed-extension + run: | + chmod +x "$GITHUB_WORKSPACE/zed-extension" + mkdir -p /tmp/ext-scratch /tmp/ext-output + "$GITHUB_WORKSPACE/zed-extension" --source-dir . --scratch-dir /tmp/ext-scratch --output-dir /tmp/ext-output + + query-format: + name: Query format + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Download ts_query_ls + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: gh release download v3.15.1 --repo ribru17/ts_query_ls --pattern ts_query_ls-x86_64-unknown-linux-gnu.tar.gz --dir "$GITHUB_WORKSPACE" + - name: ts_query_ls format --check languages + run: | + tar -xf "$GITHUB_WORKSPACE/ts_query_ls-x86_64-unknown-linux-gnu.tar.gz" -C "$GITHUB_WORKSPACE" + "$GITHUB_WORKSPACE/ts_query_ls" format --check languages || { + echo "Found unformatted queries, please format them with ts_query_ls." + echo "For easy use, install the Tree-sitter query extension:" + echo "zed://extension/tree-sitter-query" + false + } diff --git a/README.md b/README.md index ea9612a..ae4d556 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,9 @@ Syntax highlighting for Helm templates using tree-sitter, plus [helm-ls](https:/ Install from the [Zed extension store](https://zed.dev/extensions/helm). -The extension looks for `helm_ls`, then `helm-ls`, on PATH. If neither is there it downloads a helm-ls release. [yaml-language-server](https://github.com/redhat-developer/yaml-language-server) is optional; helm-ls uses it for Kubernetes schema diagnostics when it is installed. +You do not need to install helm-ls first. The extension looks for `helm_ls`, then `helm-ls`, on PATH. If neither is there, it downloads a pinned helm-ls release and reuses that binary on later Zed starts. + +[yaml-language-server](https://github.com/redhat-developer/yaml-language-server) is still required for full LSP. helm-ls shells out to it for Kubernetes schema validation. Without it you get Helm template intelligence only. You can also pin a binary: @@ -25,7 +27,7 @@ You can also pin a binary: ## File detection -`.tpl`, `.gotmpl`, `helmfile.yaml`, and `helmfile.yml` are Helm out of the box. Chart templates still share `.yaml` with ordinary YAML, so map those in `settings.json`: +This matches the [official Zed Helm docs](https://zed.dev/docs/languages/helm). `.tpl`, `.gotmpl`, `helmfile.yaml`, and `helmfile.yml` are Helm out of the box. Chart templates still share `.yaml` with ordinary YAML, so map those in `settings.json`: ```json { @@ -46,10 +48,12 @@ You can also pin a binary: } ``` -Leave `Chart.yaml` as YAML. It is chart metadata, not a template. +Leave `Chart.yaml` as YAML. It is chart metadata, not a template. Path globs such as `charts/*/templates/*.yaml` are not valid in `languages/helm/config.toml` `path_suffixes`; those stay in `file_types`. If a `.yaml` file still opens as YAML, pick Helm in the language selector once, or add the glob above. helm-ls will not start on files that stay tagged as YAML, and yaml-language-server will flag `{{ }}` as errors. +`**/values*.yaml` is included because helm-ls understands values files. + ## Language server settings helm-ls reads the `helm-ls` section of workspace configuration. Put that nested object under `lsp.helm_ls.settings` (`lsp.helm` and `lsp.helm-ls` also work). These two shapes are equivalent: @@ -94,6 +98,18 @@ Full helm-ls options: [helm-ls configuration](https://github.com/mrjosh/helm-ls/ The vendored helm grammar keeps `{}`, the rest of that line, and the trailing newline as one text token so typing at EOL after `emptyDir: {}` does not sit on the next node's start. YAML is injected per `(text)` node, not combined ([zed#57341](https://github.com/zed-industries/zed/issues/57341)). +## Testing + +```sh +cargo test +./scripts/check-queries.sh +./scripts/check-grammar.sh +./scripts/check-grammar-pin.sh +./scripts/check-zed-queries.sh +``` + +CI also packages with the `zed-extension` CLI and runs `ts_query_ls format --check languages`. + ## Credits Highlighting uses [tree-sitter-go-template](https://github.com/ngalaiko/tree-sitter-go-template), including the empty-mapping lexer fix from [tree-sitter-go-template#53](https://github.com/ngalaiko/tree-sitter-go-template/pull/53). diff --git a/languages/helm/brackets.scm b/languages/helm/brackets.scm index e874d9e..46356db 100644 --- a/languages/helm/brackets.scm +++ b/languages/helm/brackets.scm @@ -1,4 +1,11 @@ -("{{" @open "}}" @close) -("{{-" @open "-}}" @close) -("(" @open ")" @close) -("\"" @open "\"" @close) +("{{" @open + "}}" @close) + +("{{-" @open + "-}}" @close) + +("(" @open + ")" @close) + +("\"" @open + "\"" @close) diff --git a/languages/helm/config.toml b/languages/helm/config.toml index 6dd06c3..6a8bb63 100644 --- a/languages/helm/config.toml +++ b/languages/helm/config.toml @@ -25,3 +25,7 @@ brackets = [ { start = "\"", end = "\"", close = true, newline = false }, { start = "`", end = "`", close = true, newline = false }, ] +decrease_indent_patterns = [ + { pattern = "^\\s*\\{\\{-?\\s*else(\\s+if)?\\b", valid_after = ["if", "range", "with"] }, + { pattern = "^\\s*\\{\\{-?\\s*end\\b" }, +] diff --git a/languages/helm/highlights.scm b/languages/helm/highlights.scm index afdb463..b0ba807 100644 --- a/languages/helm/highlights.scm +++ b/languages/helm/highlights.scm @@ -1,5 +1,4 @@ ; Identifiers - [ (field) (field_identifier) @@ -10,7 +9,6 @@ (dot) @variable.special ; Function calls - (function_call function: (identifier) @function) @@ -19,7 +17,6 @@ field: (field_identifier) @function)) ; Operators - [ "|" ":=" @@ -33,37 +30,30 @@ (function_call function: (identifier) @function.builtin (#any-of? @function.builtin - "abbrev" "abbrevboth" "add" "add1" "add1f" "addf" "adler32sum" "ago" "all" - "and" "any" "append" "atoi" "b32dec" "b32enc" "b64dec" "b64enc" "base" - "buildCustomCert" "camelcase" "call" "cat" "ceil" "chunk" "clean" "coalesce" - "compact" "concat" "contains" "date" "dateInZone" "dateModify" "decryptAES" - "deepCopy" "deepEqual" "default" "derivePassword" "dict" "dig" "dir" "div" - "divf" "duration" "durationRound" "empty" "encryptAES" "eq" "ext" "fail" - "first" "float64" "floor" "fromJson" "fromJsonArray" "fromYaml" - "fromYamlArray" "ge" "genCA" "genPrivateKey" "genSelfSignedCert" - "genSignedCert" "get" "getHostByName" "gt" "has" "hasKey" "hasPrefix" - "hasSuffix" "html" "htmlDate" "htmlDateInZone" "htpasswd" "include" "index" - "indent" "initial" "initials" "int" "int64" "isAbs" "js" "kebabcase" "keys" - "kindIs" "kindOf" "last" "le" "len" "list" "lookup" "lower" "lt" "max" - "maxf" "merge" "mergeOverwrite" "min" "minf" "mod" "mul" "mulf" - "mustAppend" "mustCompact" "mustDateModify" "mustDeepCopy" "mustFirst" - "mustHas" "mustInitial" "mustLast" "mustMerge" "mustMergeOverwrite" - "mustPrepend" "mustRegexFind" "mustRegexFindAll" "mustRegexMatch" - "mustRegexReplaceAll" "mustRegexReplaceAllLiteral" "mustRegexSplit" - "mustRest" "mustReverse" "mustSlice" "mustToDate" "mustToJson" - "mustToPrettyJson" "mustToRawJson" "mustToToml" "mustUniq" "mustWithout" - "ne" "nindent" "nospace" "not" "now" "omit" "or" "pick" "pluck" "plural" - "prepend" "print" "printf" "println" "quote" "randAlpha" "randAlphaNum" - "randAscii" "randBytes" "randNumeric" "regexFind" "regexFindAll" - "regexMatch" "regexReplaceAll" "regexReplaceAllLiteral" "regexSplit" - "repeat" "replace" "required" "rest" "reverse" "round" "semver" - "semverCompare" "seq" "set" "sha1sum" "sha256sum" "sha512sum" "shuffle" - "slice" "snakecase" "squote" "sub" "subf" "substr" "swapcase" "ternary" - "title" "toDate" "toDecimal" "toJson" "toPrettyJson" "toRawJson" "toString" - "toStrings" "toToml" "toYaml" "toYamlPretty" "tpl" "trim" "trimAll" - "trimPrefix" "trimSuffix" "trunc" "typeIs" "typeIsLike" "typeOf" "uniq" - "unixEpoch" "unset" "until" "untilStep" "untitle" "upper" "urlJoin" - "urlParse" "urlquery" "uuidv4" "values" "without" "wrap" "wrapWith")) + "abbrev" "abbrevboth" "add" "add1" "add1f" "addf" "adler32sum" "ago" "all" "and" "any" "append" + "atoi" "b32dec" "b32enc" "b64dec" "b64enc" "base" "buildCustomCert" "camelcase" "call" "cat" + "ceil" "chunk" "clean" "coalesce" "compact" "concat" "contains" "date" "dateInZone" "dateModify" + "decryptAES" "deepCopy" "deepEqual" "default" "derivePassword" "dict" "dig" "dir" "div" "divf" + "duration" "durationRound" "empty" "encryptAES" "eq" "ext" "fail" "first" "float64" "floor" + "fromJson" "fromJsonArray" "fromYaml" "fromYamlArray" "ge" "genCA" "genPrivateKey" + "genSelfSignedCert" "genSignedCert" "get" "getHostByName" "gt" "has" "hasKey" "hasPrefix" + "hasSuffix" "html" "htmlDate" "htmlDateInZone" "htpasswd" "include" "index" "indent" "initial" + "initials" "int" "int64" "isAbs" "js" "kebabcase" "keys" "kindIs" "kindOf" "last" "le" "len" + "list" "lookup" "lower" "lt" "max" "maxf" "merge" "mergeOverwrite" "min" "minf" "mod" "mul" + "mulf" "mustAppend" "mustCompact" "mustDateModify" "mustDeepCopy" "mustFirst" "mustHas" + "mustInitial" "mustLast" "mustMerge" "mustMergeOverwrite" "mustPrepend" "mustRegexFind" + "mustRegexFindAll" "mustRegexMatch" "mustRegexReplaceAll" "mustRegexReplaceAllLiteral" + "mustRegexSplit" "mustRest" "mustReverse" "mustSlice" "mustToDate" "mustToJson" + "mustToPrettyJson" "mustToRawJson" "mustToToml" "mustUniq" "mustWithout" "ne" "nindent" + "nospace" "not" "now" "omit" "or" "pick" "pluck" "plural" "prepend" "print" "printf" "println" + "quote" "randAlpha" "randAlphaNum" "randAscii" "randBytes" "randNumeric" "regexFind" + "regexFindAll" "regexMatch" "regexReplaceAll" "regexReplaceAllLiteral" "regexSplit" "repeat" + "replace" "required" "rest" "reverse" "round" "semver" "semverCompare" "seq" "set" "sha1sum" + "sha256sum" "sha512sum" "shuffle" "slice" "snakecase" "squote" "sub" "subf" "substr" "swapcase" + "ternary" "title" "toDate" "toDecimal" "toJson" "toPrettyJson" "toRawJson" "toString" + "toStrings" "toToml" "toYaml" "toYamlPretty" "tpl" "trim" "trimAll" "trimPrefix" "trimSuffix" + "trunc" "typeIs" "typeIsLike" "typeOf" "uniq" "unixEpoch" "unset" "until" "untilStep" "untitle" + "upper" "urlJoin" "urlParse" "urlquery" "uuidv4" "values" "without" "wrap" "wrapWith")) ; Built-in chart objects: {{ .Values.foo }} and {{ $.Release.Name }} (field @@ -78,8 +68,8 @@ "Values" "Chart" "Release" "Capabilities" "Files" "Subcharts" "Template")) ; Delimiters - "." @punctuation.delimiter + "," @punctuation.delimiter [ @@ -92,7 +82,6 @@ ] @punctuation.bracket ; Keywords - [ "else" "if" @@ -107,7 +96,6 @@ ] @keyword ; Literals - [ (interpreted_string_literal) (raw_string_literal) diff --git a/languages/helm/indents.scm b/languages/helm/indents.scm new file mode 100644 index 0000000..2088e2d --- /dev/null +++ b/languages/helm/indents.scm @@ -0,0 +1,15 @@ +; Indent bodies of template control actions. `end` / `else` outdent so they +; line up with the opening action, matching everyday Helm editing. +(if_action) @indent @start.if + +(range_action) @indent @start.range + +(with_action) @indent @start.with + +(define_action) @indent + +(block_action) @indent + +"else" @outdent + +"end" @outdent diff --git a/languages/helm/injections.scm b/languages/helm/injections.scm index bea6cc0..50b4fbd 100644 --- a/languages/helm/injections.scm +++ b/languages/helm/injections.scm @@ -8,5 +8,4 @@ ; newline in one text node. An EOL insert after emptyDir: {} stays ; inside that node, so YAML for keys on later lines is not dropped. ((text) @content - (#set! "language" "yaml")) - + (#set! "language" "yaml")) diff --git a/languages/helm/textobjects.scm b/languages/helm/textobjects.scm new file mode 100644 index 0000000..505b17c --- /dev/null +++ b/languages/helm/textobjects.scm @@ -0,0 +1,6 @@ +; Named templates are the function-like unit in Helm. +(define_action) @function.around + +(block_action) @function.around + +(comment)+ @comment.around diff --git a/scripts/check-grammar-pin.sh b/scripts/check-grammar-pin.sh new file mode 100755 index 0000000..dd92875 --- /dev/null +++ b/scripts/check-grammar-pin.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# Grammar pin / generated-files gate. +# +# 1. extension.toml [grammars.helm] commit must match tests/grammar-pin.sha +# so the revision Zed downloads is the one queries are compiled against. +# 2. Prefer vendor/tree-sitter-helm in this checkout (the newline-after-{} +# lexer). Clone the pin only if vendor/ is missing. +# 3. Like ngalaiko/tree-sitter-go-template CI: regenerate the helm dialect +# and fail if committed parser artifacts drift (aside from the CLI +# version banner in parser.c). +set -euo pipefail + +# shellcheck source=lib/grammar-pin.sh +source "$(cd "$(dirname "$0")" && pwd)/lib/grammar-pin.sh" + +load_grammar_pin +assert_grammar_pin_lock + +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT +ensure_tree_sitter "$WORK" + +echo "Pin $GRAMMAR_REPO @$GRAMMAR_COMMIT ($GRAMMAR_PATH)" +echo "tree-sitter $(tree-sitter --version)" + +stage_helm_grammar "$WORK/dialect" +echo "ok grammar pin lock matches extension.toml and tests/grammar-pin.sha" + +cd "$DIALECT" +git init -q +git add -A +git -c user.name=ci -c user.email=ci@helm.zed commit -qm pin +tree-sitter generate + +# Ignore the "Automatically @generated by tree-sitter vX.Y.Z" banner so a +# patch CLI bump does not fail this gate. Real parser/node-types drift still +# fails, same as `git diff --exit-code` in the upstream grammar CI. +if ! git diff --exit-code \ + -I 'Automatically @generated by tree-sitter' \ + -- src; then + echo "generated helm grammar artifacts drifted from git at $GRAMMAR_COMMIT" >&2 + echo "Bump the pin only to a commit whose $GRAMMAR_PATH/src is generated." >&2 + exit 1 +fi + +echo "ok generated $GRAMMAR_PATH/src matches git (ignoring CLI version banner)" +echo "Grammar pin is consistent." diff --git a/scripts/check-queries.sh b/scripts/check-queries.sh new file mode 100755 index 0000000..4114004 --- /dev/null +++ b/scripts/check-queries.sh @@ -0,0 +1,119 @@ +#!/usr/bin/env bash +# Parse the example chart templates with the grammar pinned in extension.toml +# and check that Helm query files are valid against that grammar. +set -euo pipefail + +# shellcheck source=lib/grammar-pin.sh +source "$(cd "$(dirname "$0")" && pwd)/lib/grammar-pin.sh" + +load_grammar_pin +assert_grammar_pin_lock + +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT +ensure_tree_sitter "$WORK" + +echo "tree-sitter $(tree-sitter --version)" +stage_helm_grammar "$WORK/dialect" +if [[ ! -f "$DIALECT/grammar.js" ]]; then + echo "missing grammar.js in $GRAMMAR_PATH" >&2 + exit 1 +fi + +cd "$DIALECT" +fail=0 + +check_parse() { + local file="$1" + local out + if ! out="$(tree-sitter parse --rebuild "$file" -q 2>&1)"; then + echo "PARSE FAILED $file" + tree-sitter parse --rebuild "$file" 2>/dev/null | grep ERROR || true + echo "$out" + fail=1 + return + fi + echo "ok parse ${file#"$ROOT/"}" +} + +shopt -s nullglob +templates=("$ROOT"/tests/charts/example/templates/*) +if [[ ${#templates[@]} -eq 0 ]]; then + echo "no chart templates under tests/charts/example/templates" >&2 + exit 1 +fi + +for fixture in "${templates[@]}"; do + check_parse "$fixture" +done + +QUERIES=( + highlights.scm + injections.scm + outline.scm + indents.scm + brackets.scm + textobjects.scm +) + +sample="${templates[0]}" +for query in "${QUERIES[@]}"; do + path="$ROOT/languages/helm/$query" + if [[ ! -f "$path" ]]; then + echo "missing query file $query" >&2 + fail=1 + continue + fi + if ! tree-sitter query "$path" "$sample" >/dev/null 2>"$WORK/query.err"; then + echo "QUERY FAILED $query" + cat "$WORK/query.err" + fail=1 + else + echo "ok query $query" + fi +done + +# Everyday Helm captures that should survive query refactors. +query_out="$(tree-sitter query "$ROOT/languages/helm/highlights.scm" \ + "$ROOT/tests/charts/example/templates/deployment.yaml" 2>/dev/null || true)" +for cap in \ + "keyword.*text: \`if\`" \ + "keyword.*text: \`range\`" \ + "keyword.*text: \`else\`" \ + "keyword.*text: \`end\`" \ + "function.*text: \`include\`" \ + "function.builtin.*text: \`nindent\`" +do + if grep -Eq "$cap" <<<"$query_out"; then + echo "ok highlight $cap" + else + echo "missing highlight capture: $cap" + fail=1 + fi +done + +outline_out="$(tree-sitter query "$ROOT/languages/helm/outline.scm" \ + "$ROOT/tests/charts/example/templates/_helpers.tpl" 2>/dev/null || true)" +if grep -Eq 'name.*text: `"example.name"`' <<<"$outline_out"; then + echo "ok outline define example.name" +else + echo "missing outline capture for define example.name" + echo "$outline_out" + fail=1 +fi + +indent_out="$(tree-sitter query "$ROOT/languages/helm/indents.scm" \ + "$ROOT/tests/charts/example/templates/deployment.yaml" 2>/dev/null || true)" +if grep -Eq 'capture: indent' <<<"$indent_out" && grep -Eq 'text: `end`' <<<"$indent_out"; then + echo "ok indent if/range and outdent end" +else + echo "missing @indent / @outdent captures" + echo "$indent_out" + fail=1 +fi + +if [[ "$fail" -ne 0 ]]; then + exit 1 +fi + +echo "Chart fixtures parsed and queries matched expected captures." diff --git a/scripts/check-zed-queries.sh b/scripts/check-zed-queries.sh new file mode 100755 index 0000000..06abd2d --- /dev/null +++ b/scripts/check-zed-queries.sh @@ -0,0 +1,124 @@ +#!/usr/bin/env bash +# Zed-log style query load check. +# +# tree-sitter query compiles mixed @content / @injection.content, but Zed +# refuses to register the language: +# Error loading injection query: both content and injection.content captures are present +# Invalid node types (a backtick pair in brackets.scm) also fail Query::new +# and Helm disappears from the language selector. +# +# Compile every languages/helm/*.scm against the pinned helm grammar, then +# apply the capture-name rules from PR #32's check-grammar.sh. +set -euo pipefail + +# shellcheck source=lib/grammar-pin.sh +source "$(cd "$(dirname "$0")" && pwd)/lib/grammar-pin.sh" +# shellcheck source=lib/zed-queries.sh +source "$(cd "$(dirname "$0")" && pwd)/lib/zed-queries.sh" + +load_grammar_pin +assert_grammar_pin_lock + +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT +ensure_tree_sitter "$WORK" + +echo "Pin $GRAMMAR_REPO @$GRAMMAR_COMMIT ($GRAMMAR_PATH)" +echo "tree-sitter $(tree-sitter --version)" +echo "Queries compiled against $GRAMMAR_COMMIT (matches tests/grammar-pin.sha)" + +stage_helm_grammar "$WORK/dialect" + +SAMPLE="$ROOT/tests/charts/example/templates/deployment.yaml" +if [[ ! -f "$SAMPLE" ]]; then + echo "missing sample fixture $SAMPLE" >&2 + exit 1 +fi + +cd "$DIALECT" +fail=0 + +shopt -s nullglob +queries=("$ROOT"/languages/helm/*.scm) +if [[ ${#queries[@]} -eq 0 ]]; then + echo "no languages/helm/*.scm files" >&2 + exit 1 +fi + +for query in "${queries[@]}"; do + name="$(basename "$query")" + if ! tree-sitter query "$query" "$SAMPLE" >/dev/null 2>"$WORK/query.err"; then + echo "QUERY FAILED $name (Zed would not register Helm)" + cat "$WORK/query.err" + fail=1 + continue + fi + echo "ok compile $name" + + if ! zed_required_captures_ok "$query" 2>"$WORK/cap.err"; then + echo "QUERY FAILED $name: $(tr '\n' ' ' <"$WORK/cap.err")" + fail=1 + else + echo "ok zed-load $name" + fi +done + +# The exact dual-capture query Zed rejected must not pass this check. +# tree-sitter query accepts it; that is why a compile-only job is not enough. +cat >"$WORK/dual-injections.scm" <<'EOF' +((text) @content @injection.content + (#set! "language" "yaml") + (#set! "injection.language" "yaml") + (#set! "combined") + (#set! "injection.combined")) +EOF +if tree-sitter query "$WORK/dual-injections.scm" "$SAMPLE" >/dev/null 2>&1; then + echo "ok tree-sitter query accepts dual captures (Zed does not)" +else + echo "unexpected: tree-sitter query rejected dual captures" + fail=1 +fi +if zed_injection_query_ok "$WORK/dual-injections.scm" 2>"$WORK/dual.err"; then + echo "QUERY CHECK MISSED dual content captures" + fail=1 +else + echo "ok detector rejects dual captures: $(tr '\n' ' ' <"$WORK/dual.err")" +fi + +# Combined injection is the #22 incremental drop in Zed. Must not ship. +cat >"$WORK/combined-injections.scm" <<'EOF' +((text) @content + (#set! "language" "yaml") + (#set! "combined")) +EOF +if zed_injection_query_ok "$WORK/combined-injections.scm" 2>"$WORK/comb.err"; then + echo "QUERY CHECK MISSED combined injection" + fail=1 +else + echo "ok detector rejects combined injection: $(tr '\n' ' ' <"$WORK/comb.err")" +fi + +# Invalid node type that made Helm vanish: backtick is not a token, raw +# strings are (raw_string_literal). +cat >"$WORK/backtick-brackets.scm" <<'EOF' +("{{" @open "}}" @close) +("`" @open "`" @close) +EOF +if tree-sitter query "$WORK/backtick-brackets.scm" "$SAMPLE" >/dev/null 2>"$WORK/bt.err"; then + echo "QUERY CHECK MISSED invalid backtick node type" + fail=1 +else + if grep -qi 'Invalid node type' "$WORK/bt.err"; then + echo "ok detector rejects backtick brackets: $(tr '\n' ' ' <"$WORK/bt.err")" + else + echo "backtick brackets failed for an unexpected reason:" + cat "$WORK/bt.err" + fail=1 + fi +fi + +if [[ "$fail" -ne 0 ]]; then + exit 1 +fi + +echo "All Helm queries load the way Zed would register them." diff --git a/scripts/lib/grammar-pin.sh b/scripts/lib/grammar-pin.sh new file mode 100644 index 0000000..d3f4ff7 --- /dev/null +++ b/scripts/lib/grammar-pin.sh @@ -0,0 +1,79 @@ +# Shared pin for the helm grammar Zed compiles. Sourced by CI scripts. +# Keep GRAMMAR_COMMIT in sync with extension.toml [grammars.helm] commit +# and tests/grammar-pin.sha. After #32 that path is vendor/tree-sitter-helm. + +helm_zed_root() { + local here + here="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" + printf '%s\n' "$here" +} + +load_grammar_pin() { + ROOT="$(helm_zed_root)" + GRAMMAR_REPO="$(awk '/\[grammars.helm\]/{f=1} f && /^repository =/{gsub(/"/, "", $3); print $3; exit}' "$ROOT/extension.toml")" + GRAMMAR_COMMIT="$(awk '/\[grammars.helm\]/{f=1} f && /^commit =/{gsub(/"/, "", $3); print $3; exit}' "$ROOT/extension.toml")" + GRAMMAR_PATH="$(awk '/\[grammars.helm\]/{f=1} f && /^path =/{gsub(/"/, "", $3); print $3; exit}' "$ROOT/extension.toml")" + + if [[ -z "$GRAMMAR_REPO" || -z "$GRAMMAR_COMMIT" || -z "$GRAMMAR_PATH" ]]; then + echo "failed to read [grammars.helm] from extension.toml" >&2 + return 1 + fi + if [[ ! "$GRAMMAR_COMMIT" =~ ^[0-9a-f]{40}$ ]]; then + echo "extension.toml grammars.helm.commit must be a full 40-char SHA, got: $GRAMMAR_COMMIT" >&2 + return 1 + fi +} + +assert_grammar_pin_lock() { + local lock + lock="$(tr -d '[:space:]' <"$ROOT/tests/grammar-pin.sha")" + if [[ "$lock" != "$GRAMMAR_COMMIT" ]]; then + echo "grammar pin mismatch:" >&2 + echo " extension.toml [grammars.helm] commit = $GRAMMAR_COMMIT" >&2 + echo " tests/grammar-pin.sha = $lock" >&2 + echo "Bump both together so queries compile against the grammar Zed downloads." >&2 + return 1 + fi +} + +ensure_tree_sitter() { + if command -v tree-sitter >/dev/null 2>&1; then + return 0 + fi + local prefix="${1:?need npm prefix}" + npm install --silent --no-fund --no-audit --prefix "$prefix" tree-sitter-cli@0.25.10 + PATH="$prefix/node_modules/.bin:$PATH" + export PATH +} + +clone_pinned_grammar() { + local dest="${1:?need clone dest}" + git clone --quiet "$GRAMMAR_REPO" "$dest" + git -C "$dest" checkout --quiet "$GRAMMAR_COMMIT" + local head + head="$(git -C "$dest" rev-parse HEAD)" + if [[ "$head" != "$GRAMMAR_COMMIT" ]]; then + echo "cloned HEAD $head does not match pin $GRAMMAR_COMMIT" >&2 + return 1 + fi + if [[ ! -f "$dest/$GRAMMAR_PATH/grammar.js" ]]; then + echo "missing grammar.js in $GRAMMAR_PATH at $GRAMMAR_COMMIT" >&2 + return 1 + fi +} + +# Writable copy of the helm dialect. Prefer the working tree so CI tests +# the vendored newline-after-{} lexer; clone the pin if vendor/ is absent. +stage_helm_grammar() { + local dest="${1:?need dest}" + if [[ -f "$ROOT/$GRAMMAR_PATH/grammar.js" ]]; then + echo "Using local $GRAMMAR_PATH" + mkdir -p "$dest" + cp -a "$ROOT/$GRAMMAR_PATH/." "$dest/" + DIALECT="$dest" + return 0 + fi + echo "Using $GRAMMAR_REPO @$GRAMMAR_COMMIT ($GRAMMAR_PATH)" + clone_pinned_grammar "$dest/repo" + DIALECT="$dest/repo/$GRAMMAR_PATH" +} diff --git a/scripts/lib/zed-queries.sh b/scripts/lib/zed-queries.sh new file mode 100644 index 0000000..c251013 --- /dev/null +++ b/scripts/lib/zed-queries.sh @@ -0,0 +1,68 @@ +# Zed language_registry checks that tree-sitter query does not perform. +# Sourced by scripts/check-zed-queries.sh. + +# Capture names in a query file, skipping comment lines. +query_capture_names() { + local file="$1" + grep -vE '^\s*;' "$file" | grep -oE '@[A-Za-z0-9_.]+' | sed 's/^@//' | sort -u +} + +query_has_capture() { + local file="$1" name="$2" + query_capture_names "$file" | grep -qx "$name" +} + +# Mirrors crates/language/src/language.rs with_injection_query: +# mixing old (@content) and new (@injection.content) styles is a hard error +# ("Error loading injection query: both content and injection.content captures are present"). +zed_injection_query_ok() { + local file="$1" + if query_has_capture "$file" content \ + && query_has_capture "$file" injection.content; then + echo "both content and injection.content captures are present" >&2 + return 1 + fi + if query_has_capture "$file" language \ + && query_has_capture "$file" injection.language; then + echo "both language and injection.language captures are present" >&2 + return 1 + fi + if ! query_has_capture "$file" content \ + && ! query_has_capture "$file" injection.content; then + echo "missing required capture: content or injection.content" >&2 + return 1 + fi + # Combined YAML injection is zed#57341 / helm.zed#22: typing next to + # emptyDir: {} drops every YAML key. Inject each (text) node separately. + if grep -vE '^\s*;' "$file" | grep -Eq '(^|[^A-Za-z0-9_.])(injection\.)?combined($|[^A-Za-z0-9_.])'; then + echo "combined injection drops YAML on incremental parse in Zed (zed#57341)" >&2 + return 1 + fi + return 0 +} + +# Required captures Zed looks up after Query::new succeeds. +# Missing ones log an error and skip that feature; we still fail CI so +# registration does not silently drop brackets/indents/outline. +zed_required_captures_ok() { + local file="$1" + local name + name="$(basename "$file")" + case "$name" in + brackets.scm) + query_has_capture "$file" open && query_has_capture "$file" close + ;; + indents.scm) + query_has_capture "$file" indent + ;; + outline.scm) + query_has_capture "$file" item && query_has_capture "$file" name + ;; + injections.scm) + zed_injection_query_ok "$file" + ;; + *) + return 0 + ;; + esac +} diff --git a/src/binary.rs b/src/binary.rs new file mode 100644 index 0000000..f252d48 --- /dev/null +++ b/src/binary.rs @@ -0,0 +1,184 @@ +//! Path and version helpers for the helm-ls binary this extension installs. +//! +//! Kept free of `zed_extension_api` so the cache/pin rules can be unit-tested +//! on the host without compiling the WASM extension. + +pub const HELM_LS: &str = "helm_ls"; +pub const HELM_LS_HYPHENATED: &str = "helm-ls"; +/// Pinned helm-ls GitHub release tag. Bump this (and re-test) to pick up a new server. +pub const HELM_LS_VERSION: &str = "v0.5.4"; +pub const HELM_LS_GITHUB_REPO: &str = "mrjosh/helm-ls"; + +const VERSION_DIR_PREFIX: &str = "helm_ls_"; + +pub fn version_dir(version: &str) -> String { + format!("{VERSION_DIR_PREFIX}{version}") +} + +pub fn asset_name(os: &str, arch: &str, exe_suffix: &str) -> String { + format!("{HELM_LS}_{os}_{arch}{exe_suffix}") +} + +pub fn binary_relpath(version: &str, os: &str, arch: &str, exe_suffix: &str) -> String { + format!( + "{}/{}", + version_dir(version), + asset_name(os, arch, exe_suffix) + ) +} + +pub fn download_url(version: &str, os: &str, arch: &str, exe_suffix: &str) -> String { + format!( + "https://github.com/{HELM_LS_GITHUB_REPO}/releases/download/{version}/{}", + asset_name(os, arch, exe_suffix) + ) +} + +/// Directories this extension creates for downloaded helm-ls builds. +pub fn is_managed_version_dir(name: &str) -> bool { + name.starts_with(VERSION_DIR_PREFIX) +} + +/// Only previously downloaded helm-ls version dirs should be removed. +/// Never touch `languages/`, `grammars/`, or other extension files. +pub fn should_remove_managed_dir(name: &str, keep_version_dir: &str) -> bool { + is_managed_version_dir(name) && name != keep_version_dir +} + +/// Use the pinned binary when it is already on disk. No GitHub call needed. +pub fn pinned_binary_if_present( + exists: impl Fn(&str) -> bool, + version: &str, + os: &str, + arch: &str, + exe_suffix: &str, +) -> Option { + let path = binary_relpath(version, os, arch, exe_suffix); + exists(&path).then_some(path) +} + +/// Offline fallback: any previously downloaded helm-ls binary for this target. +/// Prefers the pinned version if both exist. +pub fn any_cached_binary( + dir_names: &[&str], + exists: impl Fn(&str) -> bool, + os: &str, + arch: &str, + exe_suffix: &str, +) -> Option { + let asset = asset_name(os, arch, exe_suffix); + let pinned = version_dir(HELM_LS_VERSION); + + if dir_names.contains(&pinned.as_str()) { + let path = format!("{pinned}/{asset}"); + if exists(&path) { + return Some(path); + } + } + + for name in dir_names { + if !is_managed_version_dir(name) { + continue; + } + let path = format!("{name}/{asset}"); + if exists(&path) { + return Some(path); + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pins_a_real_helm_ls_tag() { + assert!(HELM_LS_VERSION.starts_with('v')); + assert_eq!(HELM_LS_VERSION, "v0.5.4"); + } + + #[test] + fn linux_amd64_paths_match_helm_ls_release_assets() { + assert_eq!(asset_name("linux", "amd64", ""), "helm_ls_linux_amd64"); + assert_eq!(version_dir("v0.5.4"), "helm_ls_v0.5.4"); + assert_eq!( + binary_relpath("v0.5.4", "linux", "amd64", ""), + "helm_ls_v0.5.4/helm_ls_linux_amd64" + ); + assert_eq!( + download_url("v0.5.4", "linux", "amd64", ""), + "https://github.com/mrjosh/helm-ls/releases/download/v0.5.4/helm_ls_linux_amd64" + ); + } + + #[test] + fn windows_asset_keeps_exe_suffix() { + assert_eq!( + asset_name("windows", "amd64", ".exe"), + "helm_ls_windows_amd64.exe" + ); + } + + #[test] + fn darwin_arm64_asset_name() { + assert_eq!(asset_name("darwin", "arm64", ""), "helm_ls_darwin_arm64"); + } + + #[test] + fn cleanup_only_removes_other_helm_ls_version_dirs() { + let keep = "helm_ls_v0.5.4"; + assert!(should_remove_managed_dir("helm_ls_v0.5.3", keep)); + assert!(!should_remove_managed_dir(keep, keep)); + assert!(!should_remove_managed_dir("languages", keep)); + assert!(!should_remove_managed_dir("grammars", keep)); + assert!(!should_remove_managed_dir("src", keep)); + assert!(!should_remove_managed_dir("extension.wasm", keep)); + assert!(!should_remove_managed_dir("target", keep)); + } + + #[test] + fn skips_github_when_pinned_binary_is_on_disk() { + let exists = |path: &str| path == "helm_ls_v0.5.4/helm_ls_linux_amd64"; + assert_eq!( + pinned_binary_if_present(exists, "v0.5.4", "linux", "amd64", ""), + Some("helm_ls_v0.5.4/helm_ls_linux_amd64".into()) + ); + assert_eq!( + pinned_binary_if_present(|_| false, "v0.5.4", "linux", "amd64", ""), + None + ); + } + + #[test] + fn cached_lookup_prefers_pinned_over_older_builds() { + let dirs = ["languages", "helm_ls_v0.5.3", "helm_ls_v0.5.4", "grammars"]; + let exists = |path: &str| { + path == "helm_ls_v0.5.3/helm_ls_linux_amd64" + || path == "helm_ls_v0.5.4/helm_ls_linux_amd64" + }; + assert_eq!( + any_cached_binary(&dirs, exists, "linux", "amd64", ""), + Some("helm_ls_v0.5.4/helm_ls_linux_amd64".into()) + ); + } + + #[test] + fn cached_lookup_falls_back_to_an_older_build() { + let dirs = ["helm_ls_v0.5.3", "languages"]; + let exists = |path: &str| path == "helm_ls_v0.5.3/helm_ls_linux_amd64"; + assert_eq!( + any_cached_binary(&dirs, exists, "linux", "amd64", ""), + Some("helm_ls_v0.5.3/helm_ls_linux_amd64".into()) + ); + } + + #[test] + fn cached_lookup_ignores_unrelated_directories() { + let dirs = ["languages", "grammars", "target"]; + assert_eq!( + any_cached_binary(&dirs, |_| true, "linux", "amd64", ""), + None + ); + } +} diff --git a/src/helm.rs b/src/helm.rs index 32767f3..5dda83d 100644 --- a/src/helm.rs +++ b/src/helm.rs @@ -1,14 +1,20 @@ +mod binary; + use std::fs; use zed::LanguageServerId; use zed_extension_api::{self as zed, serde_json, settings::LspSettings, Result}; +use binary::{ + any_cached_binary, asset_name, binary_relpath, download_url, pinned_binary_if_present, + should_remove_managed_dir, version_dir, HELM_LS, HELM_LS_GITHUB_REPO, HELM_LS_HYPHENATED, + HELM_LS_VERSION, +}; + struct HelmExtension { cached_binary_path: Option, } impl HelmExtension { - const HELM_LS: &'static str = "helm_ls"; - const HELM_LS_HYPHENATED: &'static str = "helm-ls"; /// Keys users actually put under `lsp` in settings.json. The language /// server id in extension.toml is `helm`, the display name is `helm_ls`, /// and helm-ls's own config section is `helm-ls`. @@ -25,7 +31,7 @@ impl HelmExtension { } } } - LspSettings::for_worktree(Self::HELM_LS, worktree).unwrap_or_default() + LspSettings::for_worktree(HELM_LS, worktree).unwrap_or_default() } fn language_server_binary_path( @@ -33,129 +39,150 @@ impl HelmExtension { language_server_id: &LanguageServerId, worktree: &zed::Worktree, ) -> Result { + // 1. In-memory cache: fastest path, valid within a single Zed session. if let Some(path) = &self.cached_binary_path { if fs::metadata(path).map_or(false, |stat| stat.is_file()) { return Ok(path.clone()); } } + // 2. System-wide installation: respect an existing helm_ls or helm-ls on PATH. if let Some(path) = worktree - .which(Self::HELM_LS) - .or_else(|| worktree.which(Self::HELM_LS_HYPHENATED)) + .which(HELM_LS) + .or_else(|| worktree.which(HELM_LS_HYPHENATED)) { self.cached_binary_path = Some(path.clone()); return Ok(path); } - let (platform, arch) = zed::current_platform(); - let binary_prefix = format!("{}_", Self::HELM_LS); + let (os, arch, exe_suffix) = platform_triple(); + let exists = |path: &str| fs::metadata(path).map_or(false, |stat| stat.is_file()); - let os = match platform { - zed::Os::Mac => "darwin", - zed::Os::Linux => "linux", - zed::Os::Windows => "windows", - }; - let arch = match arch { - zed::Architecture::Aarch64 => "arm64", - zed::Architecture::X86 => "x86", - zed::Architecture::X8664 => "amd64", - }; - let extension = match platform { - zed::Os::Mac | zed::Os::Linux => "", - zed::Os::Windows => ".exe", - }; + // 3. Pinned binary already downloaded. Skip GitHub entirely so a cold + // Zed start does not call latest_github_release / the releases API. + if let Some(path) = pinned_binary_if_present(exists, HELM_LS_VERSION, os, arch, exe_suffix) + { + self.cached_binary_path = Some(path.clone()); + return Ok(path); + } - let binary_name = format!("{binary_prefix}{os}_{arch}{extension}"); - - let installed_binary_path = fs::read_dir(".").ok().and_then(|entries| { - entries - .filter_map(|e| e.ok()) - .filter(|e| { - e.file_name() - .to_str() - .map_or(false, |n| n.starts_with(&binary_prefix)) - }) - .filter_map(|dir| { - let dir_name = dir.file_name(); - let path = format!("{}/{binary_name}", dir_name.to_str()?); - if fs::metadata(&path).map_or(false, |s| s.is_file()) { - Some(path) - } else { - None - } - }) - .next() - }); + // 4. Download the pinned release. Fall back to any older cached binary + // if we are offline or GitHub is unreachable. + match self.download_pinned(language_server_id, os, arch, exe_suffix) { + Ok(path) => { + self.cached_binary_path = Some(path.clone()); + Ok(path) + } + Err(err) => { + let dirs = list_dir_names("."); + let names: Vec<&str> = dirs.iter().map(|s| s.as_str()).collect(); + if let Some(path) = any_cached_binary(&names, exists, os, arch, exe_suffix) { + self.cached_binary_path = Some(path.clone()); + return Ok(path); + } + Err(err) + } + } + } + fn download_pinned( + &self, + language_server_id: &LanguageServerId, + os: &str, + arch: &str, + exe_suffix: &str, + ) -> Result { zed::set_language_server_installation_status( language_server_id, &zed::LanguageServerInstallationStatus::CheckingForUpdate, ); - let release = match zed::latest_github_release( - "mrjosh/helm-ls", - zed::GithubReleaseOptions { - require_assets: true, - pre_release: false, - }, - ) { - Ok(release) => release, - Err(_) => { - if let Some(path) = installed_binary_path { - self.cached_binary_path = Some(path.clone()); - return Ok(path); - } - return Err(format!( - "{} is not installed and cannot be downloaded without an internet connection", - Self::HELM_LS - ) - .into()); - } - }; - let version_dir = format!("{binary_prefix}{}", release.version); - let binary_path = format!("{version_dir}/{binary_name}"); - - if !fs::metadata(&binary_path).map_or(false, |stat| stat.is_file()) { - let asset = release - .assets - .iter() - .find(|asset| asset.name == binary_name) - .ok_or_else(|| format!("no asset found matching {:?}", binary_name))?; - - fs::create_dir_all(&version_dir) - .map_err(|err| format!("failed to create directory '{version_dir}': {err}"))?; - - zed::set_language_server_installation_status( - language_server_id, - &zed::LanguageServerInstallationStatus::Downloading, - ); - - zed::download_file( - &asset.download_url, - &binary_path, - zed::DownloadedFileType::Uncompressed, - ) + let wanted = asset_name(os, arch, exe_suffix); + // Prefer the tagged release asset URL, but do not require the GitHub API + // to succeed: the download URL is deterministic for a pinned tag. + let url = zed::github_release_by_tag_name(HELM_LS_GITHUB_REPO, HELM_LS_VERSION) + .ok() + .and_then(|release| { + release + .assets + .iter() + .find(|asset| asset.name == wanted) + .map(|asset| asset.download_url.clone()) + }) + .unwrap_or_else(|| download_url(HELM_LS_VERSION, os, arch, exe_suffix)); + + let version_dir = version_dir(HELM_LS_VERSION); + let binary_path = binary_relpath(HELM_LS_VERSION, os, arch, exe_suffix); + + fs::create_dir_all(&version_dir) + .map_err(|err| format!("failed to create directory '{version_dir}': {err}"))?; + + zed::set_language_server_installation_status( + language_server_id, + &zed::LanguageServerInstallationStatus::Downloading, + ); + + zed::download_file(&url, &binary_path, zed::DownloadedFileType::Uncompressed) .map_err(|e| format!("failed to download file: {e}"))?; - zed::make_file_executable(&binary_path)?; - - let entries = - fs::read_dir(".").map_err(|e| format!("failed to list working directory: {e}"))?; - for entry in entries { - let entry = entry.map_err(|e| format!("failed to read directory entry: {e}"))?; - let name = entry.file_name(); - let Some(name) = name.to_str() else { - continue; - }; - if name.starts_with(&binary_prefix) && name != version_dir { - fs::remove_dir_all(entry.path()).ok(); - } + zed::make_file_executable(&binary_path)?; + + // Remove older helm-ls version dirs only. The previous implementation + // called remove_dir_all on every sibling, which would delete languages/ + // and grammars/ after the first download. + let entries = + fs::read_dir(".").map_err(|e| format!("failed to list working directory: {e}"))?; + for entry in entries { + let entry = entry.map_err(|e| format!("failed to read directory entry: {e}"))?; + let Some(name) = entry.file_name().to_str().map(str::to_owned) else { + continue; + }; + if should_remove_managed_dir(&name, &version_dir) { + fs::remove_dir_all(entry.path()).ok(); } } - self.cached_binary_path = Some(binary_path.clone()); Ok(binary_path) } + + fn helm_ls_configuration(&self, worktree: &zed::Worktree) -> serde_json::Value { + let user_settings = Self::lsp_settings(worktree) + .settings + .unwrap_or_else(|| serde_json::json!({})); + let yamlls_path = worktree + .which("yaml-language-server") + .or_else(|| worktree.which("yaml-language-server.js")); + inject_yamlls_path(wrap_helm_ls_settings(user_settings), yamlls_path) + } +} + +fn platform_triple() -> (&'static str, &'static str, &'static str) { + let (platform, arch) = zed::current_platform(); + let os = match platform { + zed::Os::Mac => "darwin", + zed::Os::Linux => "linux", + zed::Os::Windows => "windows", + }; + let arch = match arch { + zed::Architecture::Aarch64 => "arm64", + zed::Architecture::X86 => "x86", + zed::Architecture::X8664 => "amd64", + }; + let exe_suffix = match platform { + zed::Os::Mac | zed::Os::Linux => "", + zed::Os::Windows => ".exe", + }; + (os, arch, exe_suffix) +} + +fn list_dir_names(path: &str) -> Vec { + fs::read_dir(path) + .ok() + .into_iter() + .flatten() + .filter_map(|e| e.ok()) + .filter_map(|e| e.file_name().into_string().ok()) + .collect() } /// Pull the inner helm-ls config out of whatever shape the user wrote. @@ -268,18 +295,6 @@ impl zed::Extension for HelmExtension { } } -impl HelmExtension { - fn helm_ls_configuration(&self, worktree: &zed::Worktree) -> serde_json::Value { - let user_settings = Self::lsp_settings(worktree) - .settings - .unwrap_or_else(|| serde_json::json!({})); - let yamlls_path = worktree - .which("yaml-language-server") - .or_else(|| worktree.which("yaml-language-server.js")); - inject_yamlls_path(wrap_helm_ls_settings(user_settings), yamlls_path) - } -} - zed_extension_api::register_extension!(HelmExtension); #[cfg(test)] diff --git a/tests/charts/example/Chart.yaml b/tests/charts/example/Chart.yaml new file mode 100644 index 0000000..19d6ed5 --- /dev/null +++ b/tests/charts/example/Chart.yaml @@ -0,0 +1,6 @@ +apiVersion: v2 +name: example +description: Fixture chart for helm.zed query and parse tests +type: application +version: 0.1.0 +appVersion: "1.0.0" diff --git a/tests/charts/example/templates/_helpers.tpl b/tests/charts/example/templates/_helpers.tpl new file mode 100644 index 0000000..d16f3c8 --- /dev/null +++ b/tests/charts/example/templates/_helpers.tpl @@ -0,0 +1,8 @@ +{{- define "example.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{- define "example.labels" -}} +app.kubernetes.io/name: {{ include "example.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- end }} diff --git a/tests/charts/example/templates/configmap.yaml b/tests/charts/example/templates/configmap.yaml new file mode 100644 index 0000000..9d642c8 --- /dev/null +++ b/tests/charts/example/templates/configmap.yaml @@ -0,0 +1,12 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "example.name" . }} +data: + {{- with .Values.config }} + config.yaml: | + {{- toYaml . | nindent 4 }} + {{- end }} + {{- if not .Values.config }} + empty: "true" + {{- end }} diff --git a/tests/charts/example/templates/deployment.yaml b/tests/charts/example/templates/deployment.yaml new file mode 100644 index 0000000..fd5d34d --- /dev/null +++ b/tests/charts/example/templates/deployment.yaml @@ -0,0 +1,30 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ include "example.name" . }} + labels: + {{- include "example.labels" . | nindent 4 }} +spec: + replicas: {{ .Values.replicaCount }} + selector: + matchLabels: + app.kubernetes.io/name: {{ include "example.name" . }} + template: + metadata: + labels: + {{- include "example.labels" . | nindent 8 }} + spec: + containers: + - name: {{ .Chart.Name }} + image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" + ports: + - containerPort: {{ .Values.service.port }} + {{- if .Values.env }} + env: + {{- range $key, $value := .Values.env }} + - name: {{ $key }} + value: {{ $value | quote }} + {{- end }} + {{- else }} + env: [] + {{- end }} diff --git a/tests/charts/example/templates/service.yaml b/tests/charts/example/templates/service.yaml new file mode 100644 index 0000000..3a579be --- /dev/null +++ b/tests/charts/example/templates/service.yaml @@ -0,0 +1,10 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ include "example.name" . }} +spec: + ports: + - port: {{ .Values.service.port }} + targetPort: {{ .Values.service.port }} + selector: + app.kubernetes.io/name: {{ include "example.name" . }} diff --git a/tests/charts/example/values.yaml b/tests/charts/example/values.yaml new file mode 100644 index 0000000..8909926 --- /dev/null +++ b/tests/charts/example/values.yaml @@ -0,0 +1,6 @@ +replicaCount: 2 +image: + repository: nginx + tag: stable +service: + port: 80 diff --git a/tests/grammar-pin.sha b/tests/grammar-pin.sha new file mode 100644 index 0000000..e6af902 --- /dev/null +++ b/tests/grammar-pin.sha @@ -0,0 +1 @@ +d4a62d114ffc784cf7df8ec294d8323d590de46d