Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: handling keys with periods when flattening/unflattening #1615

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

chandraguptgosavi
Copy link

@chandraguptgosavi chandraguptgosavi commented Jan 15, 2025

Closes #1510

✅ Checklist

  • ✅ I have followed every step in the contributing guide
  • ✅ The PR title follows the convention.
  • ✅ I ran and tested the code works

Description

It addresses the issue- Objects with keys with periods in doesn't render properly.
Eg-

{
  "Key 0.002mm": 31.4,
} 

Objects like this when unflattening will not become this

{
  "Key 0": {
      "002mm": 31.4
  }
}

Instead it will be unflattening to its original condition.

Tests

Tests have been added for this change and all passed successfully.

Screenshots

Screenshot-tests

💯

Summary by CodeRabbit

  • New Features

    • Enhanced key handling in attribute flattening and unflattening processes
    • Added support for keys containing dots without losing structural information
  • Tests

    • Added comprehensive test cases for handling complex key structures
    • Verified preservation of object structure during flattening and unflattening

Copy link

changeset-bot bot commented Jan 15, 2025

⚠️ No Changeset found

Latest commit: a1eeacd

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Jan 15, 2025

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/core/src/v3/utils/flattenAttributes.ts

Oops! Something went wrong! :(

ESLint: 8.45.0

ESLint couldn't find the config "custom" to extend from. Please check that the name of the config is correct.

The config "custom" was referenced from the config file in "/.eslintrc.js".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.

Walkthrough

The changes modify the flattenAttributes and unflattenAttributes utility functions to handle keys containing periods (.) by introducing two new functions: escapeKey and unescapeKey. These functions transform keys by replacing periods with a sentinel string (__DOT__) during flattening and reverting them back during unflattening. This ensures that keys with dots are preserved correctly when processing complex object structures, preventing unintended nested object creation.

Changes

File Change Summary
packages/core/src/v3/utils/flattenAttributes.ts Added escapeKey and unescapeKey functions to handle dot-containing keys. Modified flattenAttributes to use escaped keys when constructing new prefixes.
packages/core/test/flattenAttributes.test.ts Added test cases to verify correct handling of keys with dots during flattening and unflattening processes.

Assessment against linked issues

Objective Addressed Explanation
Handle keys with periods in logging objects [TRI-4123]
Prevent incorrect object rendering with dot-containing keys

Poem

🐰 A rabbit's tale of keys so bright,
Dots escaped with magical might!
From Key 0.002mm to flat terrain,
No nested mysteries to explain,
Our data dances, pure and light! 🔍

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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
Contributor

@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: 0

🧹 Nitpick comments (2)
packages/core/src/v3/utils/flattenAttributes.ts (1)

6-15: Consider performance optimization in unescapeKey.

The RegExp object is recreated on every call to unescapeKey. Consider declaring it as a constant outside the function for better performance.

 const DOT = "__DOT__";
+const DOT_REGEX = new RegExp(DOT, "g");
 
 function escapeKey(key: string) {
   return key.replace(/\./g, DOT); // Replace . with __DOT__
 }
 
 function unescapeKey(key: string) {
-  let re = new RegExp(DOT, "g");
-  return key.replace(re, '.'); // Replace __DOT__ back with . (dot)
+  return key.replace(DOT_REGEX, '.'); // Replace __DOT__ back with . (dot)
 }
packages/core/test/flattenAttributes.test.ts (1)

183-213: Use Math.PI instead of a magic number.

Replace the hard-coded PI value with Math.PI from the standard library for better maintainability and accuracy.

-    const PI = 3.14159265359;
+    const PI = Math.PI;
     const result = flattenAttributes(PI);
     expect(result).toEqual({ "": PI });
     expect(unflattenAttributes(result)).toEqual(PI);
🧰 Tools
🪛 Biome (1.9.4)

[error] 209-209: Prefer constants from the standard library.

Unsafe fix: Use Math.PI instead.

(lint/suspicious/noApproximativeNumericConstant)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 719ae83 and 53f56db.

📒 Files selected for processing (2)
  • packages/core/src/v3/utils/flattenAttributes.ts (3 hunks)
  • packages/core/test/flattenAttributes.test.ts (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
packages/core/test/flattenAttributes.test.ts

[error] 209-209: Prefer constants from the standard library.

Unsafe fix: Use Math.PI instead.

(lint/suspicious/noApproximativeNumericConstant)

🔇 Additional comments (3)
packages/core/src/v3/utils/flattenAttributes.ts (2)

67-68: LGTM! Correct implementation of key escaping.

The escaping is properly applied only to object keys while preserving array indices, which is the expected behavior.


133-136: Consider adding error handling for malformed keys.

The implementation correctly unescapes keys, but it might be good to add validation for malformed keys containing the sentinel string.

 function unescapeKey(key: string) {
+  // Validate that the key doesn't contain malformed sentinel strings
+  if (key.includes(DOT) && !key.includes("__DOT__")) {
+    throw new Error(`Malformed key "${key}" contains partial sentinel string`);
+  }
   let re = new RegExp(DOT, "g");
   return key.replace(re, '.');
 }
✅ Verification successful

Consider adding error handling for malformed keys.

The implementation uses string replacement without validation, which could lead to ambiguous results if input keys already contain the sentinel string "DOT". The suggested validation in the review comment would prevent such cases.

  • flattenAttributes.ts: Add validation in unescapeKey() function to detect malformed keys containing partial sentinel strings.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for potential conflicts with the sentinel string in existing keys
rg -l "__DOT__" --type ts

Length of output: 118


Script:

#!/bin/bash
# Check sentinel string definition and usage
echo "=== Implementation ==="
rg -A 3 -B 3 "__DOT__" packages/core/src/v3/utils/flattenAttributes.ts

echo -e "\n=== Test Cases ==="
rg -A 3 -B 3 "__DOT__" packages/core/test/flattenAttributes.test.ts

Length of output: 1353

packages/core/test/flattenAttributes.test.ts (1)

296-314: LGTM! Comprehensive test coverage.

The test cases thoroughly verify the escaping/unescaping functionality with both simple and nested objects.

Consider adding edge cases:

  1. Keys with multiple dots
  2. Keys with the sentinel string as part of the original key
  3. Empty keys

@chandraguptgosavi
Copy link
Author

@matt-aitken Please review

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[TRI-4123] Logging objects with keys with periods in doesn't render properly in the UI
1 participant