Skip to content
This repository was archived by the owner on Jan 1, 2026. It is now read-only.

fix: interpret variables via templateSrv.replace#703

Merged
simPod merged 1 commit into
0.7.xfrom
vars
May 19, 2025
Merged

fix: interpret variables via templateSrv.replace#703
simPod merged 1 commit into
0.7.xfrom
vars

Conversation

@simPod
Copy link
Copy Markdown
Owner

@simPod simPod commented May 19, 2025

Index by name property. Grafana 12 does not have variable.id property (checked on b674c3157915f1bd16257b46889ae3a28bb790a5)

Summary by CodeRabbit

  • Refactor
    • Simplified variable value extraction logic for improved maintainability.
    • Updated variable resolution to better respect the current context.
  • Chores
    • Removed unused dependencies and obsolete utility functions.

@simPod simPod requested a review from Copilot May 19, 2025 15:59
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 19, 2025

Caution

Review failed

The pull request is closed.

"""

Walkthrough

The changes refactor variable value extraction logic in the data source by removing custom pattern matching and multi-support handling. The getVariables method now directly uses the template service's replace function with scoped variables. The helper function for multi-support variable value extraction is deleted, and the getVariables method signature is updated accordingly.

Changes

File(s) Change Summary
src/DataSource.ts Refactored variable value extraction to use template service's replace method; updated method signature for getVariables to accept optional scopedVars; removed imports of ts-pattern and custom multi-support logic.
src/variable/valueFromVariableWithMultiSupport.ts Deleted file; removed the exported helper function for extracting values from variables with multi-support.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant DataSource
    participant TemplateSrv

    Caller->>DataSource: query(options)
    DataSource->>DataSource: getVariables(scopedVars)
    DataSource->>TemplateSrv: replace($varName, scopedVars)
    TemplateSrv-->>DataSource: resolvedValue
    DataSource-->>Caller: query result
Loading

"""

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 12e96b1 and 9eda5ef.

📒 Files selected for processing (2)
  • src/DataSource.ts (3 hunks)
  • src/variable/valueFromVariableWithMultiSupport.ts (0 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR replaces a custom multi-value extraction helper with Grafana’s built-in templateSrv.replace to interpret template variables, and switches variable indexing from id to name to support Grafana 12.

  • Remove valueFromVariableWithMultiSupport.ts and its imports
  • Update getVariables method to accept existing scoped vars, use templateSrv.replace, and key by variable.name
  • Adjust merging of scoped variables before query execution

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
src/variable/valueFromVariableWithMultiSupport.ts Removed deprecated helper for multi-value variable extraction
src/DataSource.ts Refactored getVariables to use templateSrv.replace and index by name
Comments suppressed due to low confidence (1)

src/DataSource.ts:291

  • The key type for variableOptions should reflect the new use of variable.name (a string) instead of VariableWithMultiSupport['id']. Update the record type to Record<string, VariableOption> or a more specific alias.
const variableOptions: Record<VariableWithMultiSupport['id'], VariableOption> = {};

Comment thread src/DataSource.ts Outdated
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🔭 Outside diff range comments (1)
src/DataSource.ts (1)

290-312: ⚠️ Potential issue

Key type does not match the new indexing strategy

variableOptions is declared as
Record<VariableWithMultiSupport['id'], VariableOption> (i.e. a number key),
yet keys are now populated with variable.name (a string).
This will fail tsc with TS2322 in strict projects.

-const variableOptions: Record<VariableWithMultiSupport['id'], VariableOption> = {};
+const variableOptions: Record<string, VariableOption> = {};

After this change you can also remove the still-imported but now unused
VariableWithMultiSupport type alias at the top of the file.

🧹 Nitpick comments (2)
src/DataSource.ts (2)

303-304: Pass an explicit format to templateSrv.replace

templateSrv.replace defaults to the string formatter, which performs un-escaped substitutions inside JSON strings.
When variables are used in JSON payloads, this may lead to malformed JSON or double-quoting issues.

-const value = getTemplateSrv().replace('$' + variable.name, scopedVars);
+const value = getTemplateSrv().replace('$' + variable.name, scopedVars, 'json');

Using json (or regex where appropriate) ensures safe escaping and mirrors
the formatters used elsewhere in the file (processPayload, listMetrics, …).


305-308: Preserve selected state instead of hard-coding false

The builder UI might rely on the selected flag to render the current value.
Using a constant false drops that information:

-variableOptions[variable.name] = {
-  selected: false,
-  text: variable.current.text,
-  value: value,
-};
+variableOptions[variable.name] = {
+  selected: variable.current.selected ?? false,
+  text:     variable.current.text,
+  value,
+};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b8d8b91 and 5f59092.

📒 Files selected for processing (2)
  • src/DataSource.ts (3 hunks)
  • src/variable/valueFromVariableWithMultiSupport.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • src/variable/valueFromVariableWithMultiSupport.ts
🧰 Additional context used
🪛 GitHub Actions: CI
src/DataSource.ts

[error] 1-1: Prettier formatting check failed. Run 'prettier --write' to fix code style issues in this file.

🔇 Additional comments (1)
src/DataSource.ts (1)

1-315: Run Prettier ‑ formatting check is failing

CI reports a Prettier failure for this file.
Run prettier --write src/DataSource.ts (or npm run format) to keep the
commit stream green.

🧰 Tools
🪛 Biome (1.9.4)

[error] 220-220: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🪛 GitHub Actions: CI

[error] 1-1: Prettier formatting check failed. Run 'prettier --write' to fix code style issues in this file.

Comment thread src/DataSource.ts Outdated
Index by name property. Grafana 12 does not have `variable.id` property (checked on b674c3157915f1bd16257b46889ae3a28bb790a5)
@simPod simPod merged commit 9d1273f into 0.7.x May 19, 2025
5 of 6 checks passed
@simPod simPod deleted the vars branch May 19, 2025 16:10
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants